MagicObject\DataTable
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class DataTable
Represents a data table for managing and rendering structured data. This class supports dynamic loading of data, multi-language support, and provides methods for manipulating the table's structure and appearance.
The DataTable class can be used to create HTML tables dynamically based on the provided data, with support for property annotations to manage labels and attributes.
Constants
Properties
Declaration
Description
Current language code.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Language instances.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Table identity.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Table information.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Labels for the table.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
string $code,
object|stdClass|array $reference,
bool $use = false
) : self
{
}
Description
Adds a language to the table for multi-language support.
This method registers a language instance, which can be used to retrieve labels in the specified language.
Parameters
Language code (e.g., 'en', 'fr').
Reference for language data.
Indicates whether to set this language as the current one.
Return
Returns the current instance for method chaining.
Declaration
string $code
) : self
{
}
Description
Removes a specified language from the table.
If the removed language was the current one, the first remaining language will be selected as the new current language.
Parameters
Language code to remove.
Return
Returns the current instance for method chaining.
Declaration
string $code
) : self
{
}
Description
Sets the current language for label retrieval.
This method updates the language code used for displaying labels.
Parameters
Language code to set as current.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Initializes the table's attributes and configurations based on annotations.
This method parses the class annotations to set attributes, class lists, and preferred language settings.
Return
Returns the current instance for method chaining.
Declaration
PicoAnnotationParser $reflexProp,
PicoGenericObject $parameters,
string $annotation,
string $attribute
) : mixed|null
{
}
Description
Retrieves the content of a specified annotation.
This method checks for the existence of an annotation and retrieves its attribute value if it exists.
Parameters
Class reflection for parsing annotations.
Parameters for the annotation.
Annotation key to look up.
Attribute key for the annotation value.
Return
The value of the annotation attribute or null if not found.
Declaration
PicoAnnotationParser $reflexProp,
PicoGenericObject $parameters,
string $key,
string $defaultLabel
) : string
{
}
Description
Defines the label for a property based on its annotations.
This method retrieves and selects the appropriate label for a given property, falling back to default behavior if necessary.
Parameters
Class reflection for property.
Parameters associated with the property.
Property key for which to retrieve the label.
Default label to use if no annotation is found.
Return
The determined label for the property.
Declaration
DOMDocument $doc,
DOMNode $tbody,
array $props,
string $className
) : self
{
}
Description
Appends table rows based on class properties.
This method generates rows for the table based on the properties of the class and appends them to the provided DOM node.
Parameters
The DOM document used to create elements.
The DOM node representing the
of the table.Array of ReflectionProperty objects representing class properties.
Name of the class for reflection.
Return
Returns the current instance for method chaining.
Declaration
DOMDocument $doc,
DOMNode $tbody,
stdClass $values
) : self
{
}
Description
Appends table rows based on provided values.
This method takes an array of values and creates rows in the table, appending them to the provided DOM node.
Parameters
The DOM document used to create elements.
The DOM node representing the
of the table.Data to append as rows.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : string
{
}
Description
Gets the label for a specified property.
This method retrieves the label associated with a property, checking for language-specific labels before falling back to default labels.
Parameters
Name of the property for which to retrieve the label.
Return
The label for the specified property.
Declaration
string $className
) : self
{
}
Description
Adds a CSS class to the table.
This method appends a class to the table's class list, ensuring that there are no duplicates.
Parameters
Class name to add to the table.
Return
Returns the current instance for method chaining.
Declaration
string $className
) : self
{
}
Description
Removes a CSS class from the table.
This method filters out the specified class from the table's class list.
Parameters
Class name to remove from the table.
Return
Returns the current instance for method chaining.
Declaration
string $search,
string $replace
) : self
{
}
Description
Replaces a class in the table with a new class name.
Parameters
Class name to search for.
Class name to replace with.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets table information.
Return
MagicObject\Getter
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class Getter
This class provides dynamic property access and management for instances of the MagicObject framework. It allows for loading data into an object from various formats and supports retrieving property values, including handling naming conventions and formatting for JSON output.
Key Features:
- Dynamically load data from associative arrays or objects.
- Retrieve property values using both explicit getter methods and dynamic method calls.
- Convert object properties into a structured representation suitable for JSON encoding.
- Support for property naming strategies (snake case and pretty formatting) for JSON output.
Constants
Properties
Declaration
Description
Class parameters that configure behavior such as JSON output formatting.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Constructor that initializes class parameters based on annotations.
Declaration
stdClass|array $data
)
{
}
Description
Load data into the object.
Parameters
Data to load, which can be an associative array or object.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get the value of a specified property.
Parameters
Name of the property to retrieve.
Return
The value of the property, or null if not set.
Declaration
bool $snakeCase = false
) : stdClass|array
{
}
Description
Retrieve all properties as a structured object or array.
Parameters
If true, convert property names to snake case.
Return
The object containing property values, or an array if snakeCase is true.
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array|ReflectionProperty[]
{
}
Description
List properties of the current object.
Parameters
If true, include properties declared in this class.
If true, return properties as an array of strings.
Return
List of properties or an array of property names.
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method for handling calls to undefined methods.
Parameters
Name of the called method.
Parameters passed to the method.
Return
The result of the method call, if applicable.
Declaration
{
}
Description
Check if the JSON naming strategy is snake case.
Return
True if the naming strategy is snake case, false otherwise.
Declaration
{
}
Description
Determine if JSON output should be prettified.
Return
True if prettification is enabled, false otherwise.
Declaration
{
}
Description
Convert the object to a JSON string representation.
Return
A JSON representation of the object, formatted based on the naming strategy.
MagicObject\MagicDto
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class MagicDto
Represents a dynamic data transfer object that allows the user to create and manipulate properties on-the-fly. It can handle various data sources including INI, YAML, JSON, and databases. Users can perform CRUD operations on database records and manipulate properties as needed.
Constants
Properties
Declaration
Description
Class parameters.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Data source.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
self|array|stdClass|MagicObject|SetterGetter|SecretObject|PicoGenericObject|null $data = null
)
{
}
Description
Constructor.
Initializes the object with provided data and database connection.
Parameters
Initial data to populate the object.
Declaration
mixed $object
) : mixed
{
}
Description
Before loading data.
This method is called before loading data into the object. Users can override this method to manipulate the object as needed.
Parameters
The object to manipulate before loading data.
Return
The manipulated object.
Declaration
self|array|stdClass|MagicObject|SetterGetter|SecretObject|PicoGenericObject|null $data
) : self
{
}
Description
Loads data into the object.
This method accepts various data types, including:
- An instance of the class itself
- An array
- A standard object (stdClass)
-
Other specific object types such as MagicObject, SetterGetter, SecretObject, and PicoGenericObject.
The method processes the input data and stores it in the internal data source of the object, ensuring that only non-scalar values are handled.
Parameters
Return
Returns the current instance for method chaining.
Declaration
string $xmlString
) : self
{
}
Description
Loads XML data into the object.
This method accepts an XML string, converts it to an object representation, and then loads the resulting data into the internal data source of the object. It processes the XML input, ensuring that only non-scalar values are handled appropriately. This method is useful for integrating with external XML data sources.
Parameters
The XML string to load into the object.
Return
Returns the current instance for method chaining.
Throws
If the XML string is invalid or cannot be parsed.
Declaration
{
}
Description
Retrieves an object containing the values of the properties of the current instance.
This method iterates through the properties of the instance, excluding inherited properties, and constructs an object where each property is mapped to its corresponding value. The method handles various property types including self-references, magic objects, DateTime instances, and standard class objects.
Return
An object containing the values of the properties, where each property
Declaration
string $var
) : mixed|null
{
}
Description
Creates an instance of a class based on the provided variable name.
This method checks if the class corresponding to the given variable name exists. If it does, an instance of that class is created and returned; otherwise, null is returned.
Parameters
The name of the class to instantiate.
Return
An instance of the class if it exists, or null if the class does not exist.
Declaration
DateTime|null $dateTime,
object $class,
string $property
) : string|null
{
}
Description
Formats a DateTime object according to specified JSON format parameters.
This method checks if the provided DateTime object is set and, if so, retrieves formatting parameters from the property's annotations. If a 'JsonFormat' parameter is present, its pattern is used; otherwise, a default format of 'Y-m-d H:i:s' is applied.
Parameters
The DateTime object to format.
The class instance from which the property originates.
The name of the property being processed.
Return
The formatted date as a string, or null if the DateTime is not set.
Declaration
string|int $dateString
) : DateTime|null
{
}
Description
Parse DateTime from a string or Unix timestamp.
This method attempts to parse a given date string or Unix timestamp into a DateTime object using multiple predefined formats. If the parsing is successful, it returns the corresponding DateTime object; otherwise, it returns null.
Parameters
The date string or Unix timestamp to be parsed.
Return
Returns a DateTime object if parsing is successful,
Declaration
string $key
) : string|null
{
}
Description
Retrieves the documentation comment for a specified property.
Parameters
The name of the property.
Return
The documentation comment for the property, or null if not found.
Declaration
string $doc
) : string|null
{
}
Description
Extracts the source from the documentation comment.
Parameters
The documentation comment containing the source.
Return
The extracted source or null if not found.
Declaration
string $doc
) : string|null
{
}
Description
Extracts the JSON property name from the documentation comment.
Parameters
The documentation comment containing the JSON property.
Return
The extracted JSON property name or null if not found.
Declaration
string $doc
) : string|null
{
}
Description
Extracts the variable type from the documentation comment.
Parameters
The documentation comment containing the variable type.
Return
The extracted variable type or null if not found.
Declaration
string $doc
) : string|null
{
}
Description
Extracts the label from the documentation comment.
Parameters
The documentation comment containing the label.
Return
The extracted label or null if not found.
Declaration
string|null $source,
string $var,
string $propertyName
) : mixed
{
}
Description
Handles the case where the property is a self-instance.
This method retrieves the value from the data source based on the provided source or property name. If the source indicates a nested property, it retrieves that value instead. It constructs an instance of the specified class type and returns its stringified value.
Parameters
The source to extract the value from.
The variable type (class name) to instantiate.
The name of the property to fall back on.
Return
The handled value for the self-instance.
Declaration
mixed $objectTest
) : bool
{
}
Description
Checks if the given variable is a self-instance.
Parameters
The object to test against.
Return
True if it's a self-instance, otherwise false.
Declaration
mixed $objectTest
) : bool
{
}
Description
Checks if the given object is an instance of MagicObject or its derivatives.
Parameters
The object to test.
Return
True if it is a MagicObject instance, otherwise false.
Declaration
mixed $objectTest
) : bool
{
}
Description
Checks if the given object is an instance of DateTime or its derivatives.
Parameters
The object to test.
Return
True if it is a MagicObject instance, otherwise false.
Declaration
string|null $source,
string $propertyName
) : mixed
{
}
Description
Handles the case where the property is an instance of MagicObject.
This method retrieves the value from the data source and checks if it is an instance of MagicObject or its derivatives. If so, it returns the stringified value; otherwise, it returns a JSON-encoded version.
Parameters
The source to extract the value from.
The name of the property.
Return
The handled value for the MagicObject instance.
Declaration
string|null $source,
string $propertyName
) : DateTime|null
{
}
Description
Handles the case where the property is an instance of DateTime.
This method retrieves the value from the data source and parses it into a DateTime object, either from the source or a nested value.
Parameters
The source to extract the value from.
The name of the property.
Return
The handled DateTime value or null if not applicable.
Declaration
string|null $source,
string $key
) : mixed
{
}
Description
Handles the default case when retrieving property values.
This method delegates the handling of standard class properties to another method.
Parameters
The source to extract the value from.
The key of the property.
Return
The handled default value.
Declaration
string|null $source,
string $key
) : mixed
{
}
Description
Handles the stdClass when retrieving property values.
This method retrieves the value from the data source based on the given source or key, accounting for nested properties if necessary.
Parameters
The source to extract the value from.
The key of the property.
Return
The retrieved value or null if not found.
Declaration
string $source
) : mixed
{
}
Description
Retrieves nested values from the data source based on a specified source string.
This method splits the source string by the "->" delimiter to navigate through nested properties in the data source, returning the final nested value found.
Parameters
The source string indicating the path to the value.
Return
The nested value retrieved from the data source, or null if not found.
Declaration
{
}
Description
Get the object value as a specified format.
This method creates a clone of the current object and transforms its properties into a value representation, returning the object as an instance of stdClass.
Return
An object representing the value of the instance.
Declaration
{
}
Description
Get the object value as an associative array.
This method converts the object's value representation into an associative array.
Return
An associative array representing the object values.
Declaration
{
}
Description
Get the object value as an associative array with the first letter of each key in upper camel case.
This method transforms the keys of the associative array representation of the object values to be in upper camel case format.
Return
An associative array with keys in upper camel case.
Declaration
{
}
Description
Check if the JSON output should be prettified.
This method checks the class parameters to determine if JSON output formatting should be applied to enhance readability.
Return
True if JSON output is set to be prettified; otherwise, false.
Declaration
{
}
Description
Check if the XML output should be prettified.
This method checks the class parameters to determine if XML output formatting should be applied to enhance readability.
Return
True if XML output is set to be prettified; otherwise, false.
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array
{
}
Description
Retrieves a list of properties from the current class or its parent class.
This method uses reflection to obtain the properties defined in the class. It can return either the property names as an array or the ReflectionProperty objects, depending on the specified flags.
Parameters
Flag indicating whether to reflect properties of the current class (true) or the parent class (false).
Flag indicating whether to return property names as an array (true) or as ReflectionProperty objects (false).
Return
An array of property names or ReflectionProperty objects, based on the provided flags.
Declaration
self|array $value
) : mixed
{
}
Description
Recursively converts an object or an array of objects to their string representation.
This method traverses through an object or an array of objects of the same class and calls their respective stringify methods, if applicable. The final output is the stringified representation of the object or array.
Parameters
The object or array of objects to stringify.
Return
The stringified object or array.
Declaration
string $xmlString
) : stdClass
{
}
Description
Convert XML to an object.
This function takes an XML string as input and returning it as a stdClass object.
Parameters
The XML string to be converted.
Return
An object representation of the XML data.
Throws
If the XML is invalid or cannot be parsed.
Declaration
{
}
Description
Magic method to convert the object to a JSON string representation.
This method recursively converts the object's properties into JSON format. If any property is an instance of the same class, it will also be stringified. The output can be formatted for readability based on the JSON annotation of the class.
Return
A JSON representation of the object, potentially formatted for readability.
Declaration
{
}
Description
Magic method to convert the object to a JSON string representation.
This method recursively converts the object's properties into JSON format. If any property is an instance of the same class, it will also be stringified. The output can be formatted for readability based on the JSON annotation of the class.
Return
A JSON representation of the object, potentially formatted for readability.
Declaration
{
}
Description
Convert the object to a JSON object.
This method decodes the JSON string representation of the object
(produced by the __toString() method) and returns it as a PHP
object. This is useful for working with the data in a more
structured format rather than as a JSON string.
Return
A PHP object representation of the JSON data, or null if decoding fails.
Declaration
{
}
Description
Convert the object to an associative array.
This method decodes the JSON string representation of the object
(produced by the __toString() method) and returns it as an
associative array. This is useful for accessing the object's
properties in a more straightforward array format.
Return
An associative array representation of the JSON data, or null if decoding fails.
Declaration
string $root = 'root'
) : string
{
}
Description
Convert the object's properties to XML format.
This method generates an XML representation of the object based on its properties. The XML structure is built from the object's properties, and the output can be formatted for readability based on the XML annotation of the class.
Parameters
The name of the root element in the XML structure.
Return
XML representation of the object's properties, potentially formatted for readability.
Throws
If the JSON representation of the object is invalid.
Declaration
array $dataArray,
SimpleXMLElement $xml
) : void
{
}
Description
Converts an array to XML format and appends it to a SimpleXMLElement.
This function takes an associative or indexed array and recursively converts it into XML elements. Keys in the array are sanitized to ensure they are valid XML element names. Values that are not arrays are added as child elements.
Parameters
The array to convert to XML.
The XML element to which the converted data will be appended.
Return
This function does not return a value. It modifies the provided XML element.
Declaration
string $childClass,
string $methodName
) : bool
{
}
Description
Check if a method is overridden in a child class.
This method uses reflection to determine if a given method is overridden in the specified child class. It compares the methods of the child class with those of its parent class, checking if the method is present in both classes but has been redefined in the child class.
Parameters
The child class name or instance to check for method override.
The name of the method to check for overriding.
Return
Returns true if the method is overridden in the child class, false otherwise.
MagicObject\MagicObject
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class for creating a magic object. A magic object is an instance created from any class, allowing the user to add any property with any name and value. It can load data from INI files, YAML files, JSON files, and databases. Users can create entities from database tables and perform insert, select, update, and delete operations on records in the database. Users can also create properties from other entities using the full name of the class (namespace + class name).
Constants
Properties
Declaration
Description
Indicates whether the object is read-only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Database connection instance.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Class containing a database entity.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Class parameters.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
List of null properties.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Property labels.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Table information instance.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Database persistence instance.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Retrieves the list of null properties.
Return
The list of properties that are currently null.
Declaration
self|array|stdClass|object|null $data = null,
PicoDatabase|PDO|null $database = null
)
{
}
Description
Constructor.
Initializes the object with the provided data and optionally connects to a database. The constructor can accept different types of data to populate the object and can also accept a PDO connection or a PicoDatabase instance to set up the database connection.
Parameters
Initial data to populate the object. This can be:
A database connection instance, either:
Throws
If the annotations are invalid or cannot be parsed.
Declaration
mixed $data
) : self
{
}
Description
Loads data into the object.
Parameters
Data to load, which can be another MagicObject, an array, or an object.
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false
) : self
{
}
Description
Load data from an INI string.
Parameters
Raw INI data
Flag to indicate whether to use environment variables
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false
) : self
{
}
Description
Load data from an INI file.
Parameters
File path to the INI file
Flag to indicate whether to use environment variables
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Load data from a YAML string.
Parameters
YAML string
Replace all environment variable values
Result as an object instead of an array
Convert all objects to MagicObject
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Load data from a YAML file.
Parameters
File path to the YAML file
Replace all environment variable values
Result as an object instead of an array
Convert all objects to MagicObject
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Load data from a JSON string.
Parameters
JSON string
Replace all environment variable values
Result as an object instead of an array
Convert all objects to MagicObject
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Loads data from a JSON file and processes it based on the provided options.
Parameters
The file path to the JSON file.
Whether to replace system environment variables in the data (default: false).
Whether to return the result as an object instead of an associative array (default: false).
Whether to recursively convert all objects into MagicObject instances (default: false).
Return
Returns the current instance for method chaining.
Throws
If the specified JSON file does not exist.
Declaration
mixed $data,
bool $asObject,
bool $recursive
) : self
{
}
Description
Loads processed JSON data and optionally converts it to objects or parses recursively.
Parameters
The processed data to load (array or object).
Whether to return the result as an object.
Whether to recursively convert all objects into MagicObject instances.
Return
Returns the current instance for method chaining.
Declaration
bool $readonly
) : self
{
}
Description
Set the read-only state of the object.
When set to read-only, setters will not change the value of its properties, but loadData will still function normally.
Parameters
Flag to set the object as read-only
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Check if database is connected or not
Return
Returns true if the database is connected, false otherwise.
Declaration
PicoDatabase $database
) : self
{
}
Description
Set the database connection.
Parameters
Database connection
Return
Returns the current instance for method chaining.
Declaration
PicoDatabase|null $database = null
) : PicoDatabase|null
{
}
Description
Set or get the current database connection.
If the parameter is not empty, set the current database to the provided value. Otherwise, return the current database or null.
Parameters
Database connection
Return
Declaration
MagicObject|PicoDatabaseEntity|null $databaseEntity = null
) : self|PicoDatabaseEntity
{
}
Description
Set or get the database entity.
If a database entity is provided, it will be set; otherwise, the current database entity will be returned.
Parameters
The database entity to set or null to get the current entity.
Return
Returns the current instance for method chaining, or the current database entity if no parameter is provided.
Declaration
object|array $sourceData,
array $propertyNames
) : object|array
{
}
Description
Remove properties except for the specified ones.
Parameters
Data to filter
Names of properties to retain
Return
Filtered data
Declaration
bool $includeNull = false
) : PDOStatement
{
}
Description
Save the current object to the database.
This method persists the current object to the database. If $includeNull is TRUE,
all properties of the object, including those with null values, will be saved.
If FALSE, only the properties with non-null values will be saved.
Parameters
If TRUE, all properties, including null, will be saved.
Return
Returns a PDOStatement object for further database interaction.
Throws
If there is no active database connection.
If no corresponding record is found.
If a database error occurs.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}
Description
Generate a query to save data to the database.
This method prepares a query to persist the current object to the database.
If $includeNull is TRUE, properties with null values will be included in the query.
If FALSE, only properties with non-null values will be included.
Parameters
If TRUE, all properties, including null, will be saved.
Return
Returns a PicoDatabaseQueryBuilder object for query construction.
Throws
If there is no active database connection.
If no corresponding record is found.
Declaration
{
}
Description
Select data from the database.
This method retrieves data from the database. If no data is found, a NoRecordFoundException will be thrown.
The retrieved data is then loaded into the current instance for further use.
Return
Returns the current instance for method chaining.
Throws
If there is no active database connection.
If no records are found in the database.
If a database error occurs.
Declaration
{
}
Description
Select all data from the database.
This method retrieves all data from the database. If no data is found, a NoRecordFoundException will be thrown.
The retrieved data is then loaded into the current instance for further use.
Return
Returns the current instance for method chaining.
Throws
If there is no active database connection.
If no records are found in the database.
If a database error occurs.
Declaration
{
}
Description
Generate a query to select data.
This method prepares a query to select data from the database. The query can then be used to execute the retrieval of data manually if needed.
Return
Returns a PicoDatabaseQueryBuilder object for building the select query.
Throws
If there is no active database connection.
If a database error occurs.
Declaration
{
}
Description
Executes a database query based on the parameters and annotations from the caller function.
This method uses reflection to extract the query string and return type from the caller's docblock, binds the provided parameters, and executes the query against the database.
It analyzes the parameters and return type of the caller function to enable dynamic query execution tailored to the specified return type. Supported return types include:
void: Returns null.intorinteger: Returns the number of affected rows.objectorstdClass: Returns a single result as an object.stdClass[]: Returns all results as an array of stdClass objects.array: Returns all results as an associative array.string: Returns the JSON-encoded results.PDOStatement: Returns the prepared statement for further operations if needed.MagicObjectand its derived classes: If the return type is a class name or an array of class names, instances of that class will be created for each row fetched.MagicObject[]and its derived classes: Instances of the corresponding class will be created for each row fetched.
Return
The result based on the return type of the caller function:
Throws
If there is an error executing the database query.
If there is no query to be executed or if the input is invalid.
If the return type specified in the docblock is invalid or unrecognized.
Declaration
bool $includeNull = false
) : PDOStatement
{
}
Description
Insert data into the database.
This method inserts the current objectΓÇÖs data into the database. If $includeNull is TRUE,
properties with null values will also be included in the insert query. If FALSE, only properties with non-null values will be inserted.
Parameters
If TRUE, all properties, including null, will be inserted. If FALSE, only non-null values will be inserted.
Return
Returns a PDOStatement object for further database interaction.
Throws
If there is no active database connection.
If there is an error executing the insert query.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}
Description
Get the query for inserting data.
This method prepares a query to insert data into the database. It can be used to manually execute the query.
If $includeNull is TRUE, properties with null values will be included in the query. If FALSE, only non-null properties will be inserted.
Parameters
If TRUE, all properties, including null, will be included in the insert query. If FALSE, only non-null properties will be included.
Return
Returns a PicoDatabaseQueryBuilder object for building the insert query.
Throws
If there is no active database connection.
Declaration
bool $includeNull = false
) : PDOStatement
{
}
Description
Update data in the database.
This method updates the current object's data in the database. If $includeNull is TRUE,
properties with null values will be included in the update query. If FALSE, only properties with non-null values will be updated.
Parameters
If TRUE, all properties, including null, will be updated. If FALSE, only non-null values will be updated.
Return
Returns a PDOStatement object for further database interaction.
Throws
If there is no active database connection.
If there is an error executing the update query.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}
Description
Get the query for updating data.
This method prepares a query to update data in the database. It can be used to manually execute the query.
If $includeNull is TRUE, properties with null values will be included in the update query. If FALSE, only non-null properties will be updated.
Parameters
If TRUE, all properties, including null, will be included in the update query. If FALSE, only non-null properties will be included.
Return
Returns a PicoDatabaseQueryBuilder object for building the update query.
Throws
If there is no active database connection.
Declaration
{
}
Description
Delete data from the database.
This method deletes data associated with the current object from the database.
Return
Returns a PDOStatement object for further database interaction.
Throws
If there is no active database connection.
If there is an error executing the delete query.
Declaration
{
}
Description
Get the query for deleting data.
This method prepares a query to delete data from the database. It can be used to manually execute the query.
Return
Returns a PicoDatabaseQueryBuilder object for building the delete query.
Throws
If there is no active database connection.
Declaration
{
}
Description
Starts a database transaction.
This method begins a new database transaction. It delegates the actual transaction
initiation to the transactionalCommand method, passing the "start" command.
Return
Returns the current instance for method chaining.
Throws
If there is no active database connection.
If there is an error while starting the transaction.
Declaration
{
}
Description
Commits the current database transaction.
This method commits the current transaction. If successful, it makes all database
changes made during the transaction permanent. It delegates to the transactionalCommand method
with the "commit" command.
Return
Returns the current instance for method chaining.
Throws
If there is no active database connection.
If there is an error during the commit process.
Declaration
{
}
Description
Rolls back the current database transaction.
This method rolls back the current transaction, undoing all database changes made
during the transaction. It calls the transactionalCommand method with the "rollback" command.
Return
Returns the current instance for method chaining.
Throws
If there is no active database connection.
If there is an error during the rollback process.
Declaration
PicoSpecification $specification
) : PicoDatabasePersistenceExtended
{
}
Description
Get a MagicObject with a WHERE specification.
This method applies a WHERE condition to the database query using the provided specification.
The specification is an instance of PicoSpecification which defines the filtering criteria.
Parameters
The specification to define the WHERE condition.
Return
Returns an instance of PicoDatabasePersistenceExtended
Throws
If there is no active database connection.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Modify properties with null values.
This method tracks properties that are assigned a null value, storing them in a _nullProperties array.
If a property is set to null, it is added to the _nullProperties array; if it's set to a non-null value, it is removed from the array.
Parameters
The name of the property to check and modify.
The value to be assigned to the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed|null $propertyValue,
bool $skipModifyNullProperties = false
) : self
{
}
Description
Set property value.
Parameters
Property name
Property value
Skip modifying null properties
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Adds an element to the end of an array property.
Parameters
Property name
Property value
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Adds an element to the end of an array property (alias for push).
Parameters
Property name
Property value
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Adds an element to the beginning of an array property.
Parameters
Property name
Property value
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Adds an element to the beginning of an array property (alias for unshift).
Parameters
Property name
Property value
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed
{
}
Description
Remove and return the last element of an array property.
This method removes the last element from an array property and returns it. If the specified property is not an array or does not exist, null is returned.
Parameters
The name of the property (array) from which the last element will be removed.
Return
The last element of the array, or null if the property is not an array or doesn't exist.
Declaration
string $propertyName
) : mixed
{
}
Description
Remove and return the first element of an array property.
This method removes the first element from an array property and returns it. If the specified property is not an array or does not exist, null is returned.
Parameters
The name of the property (array) from which the first element will be removed.
Return
The first element of the array, or null if the property is not an array or doesn't exist.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get the value of a property.
This method retrieves the value of the specified property. If the property does not exist, it returns null.
Parameters
The name of the property to retrieve.
Return
The value of the property, or null if the property is not set.
Declaration
string $propertyName
) : bool
{
}
Description
Check if a property has a value set.
This method checks if the specified property is set (exists and has a value). It returns true if the property exists and has a value, and false otherwise.
Parameters
The name of the property to check.
Return
True if the property is set, false otherwise.
Declaration
string $propertyName,
mixed|null $defaultValue = null
) : mixed|null
{
}
Description
Get the value of a property or a default value if the property is not set.
This method retrieves the value of the specified property. If the property is not set, the provided default value is returned.
Parameters
The name of the property to retrieve.
The default value to return if the property is not set.
Return
The value of the property, or the default value if the property is not set.
Declaration
string $propertyName,
mixed $propertyValue
)
{
}
Description
Set property value (magic setter).
Parameters
Property name
Property value
Declaration
string $propertyName
) : mixed|null
{
}
Description
Magic method to get the value of a property.
This method is automatically called when an undefined or inaccessible property is accessed.
It checks if the property has been set (including null values) using the __isset method and
retrieves its value via the get method if it exists.
Parameters
The name of the property to retrieve.
Return
The value of the property if it is set, or null if the property is not set or accessible.
Declaration
string $propertyName
) : bool
{
}
Description
Magic method to check if a property is set (including null).
This method is automatically called when checking if an undefined or inaccessible property is set
using isset(). It checks if the property exists and is set (even if its value is null).
Parameters
The name of the property to check.
Return
True if the property is set (including null), false otherwise.
Declaration
string $propertyName
) : void
{
}
Description
Magic method to unset a property.
This method is automatically called when a property is unset using unset().
It unsets the specified property from the object.
Parameters
The name of the property to unset.
Return
Declaration
self|mixed $source,
array|null $filter = null,
bool $includeNull = false
) : self
{
}
Description
Copy values from another object to the current instance.
This method copies property values from the provided source object to the current instance. Optionally, a filter can be applied to specify which properties to copy, and whether null values should be included.
Parameters
The source object or data from which values will be copied. If a non-object is provided, this may result in unexpected behavior.
An optional array of property names to filter which properties are copied. If null, all properties are copied.
Flag indicating whether to include properties with null values. If false, properties with null values will be excluded from the copy.
Return
Returns the current instance for method chaining after copying the values.
Declaration
string $propertyName,
bool $skipModifyNullProperties = false
) : self
{
}
Description
Remove property value and set it to null.
Parameters
Property name
Skip modifying null properties
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Retrieve table information for the current instance.
This method retrieves the table information (e.g., schema, columns) associated with the current object. It lazily loads the table information, meaning it will be fetched only once and cached for future calls to improve performance.
Return
Returns an instance of the PicoTableInfo class containing the table schema and other related metadata.
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get default values for properties
Parameters
Flag indicating whether to convert property names to snake case
Return
An object containing default values
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get the object values
Parameters
Flag indicating whether to convert property names to snake case
Return
An object containing the values of the properties
Declaration
boolean|null $snakeCase = null
) : stdClass
{
}
Description
Get the object value as a specified format
Parameters
Flag indicating whether to convert property names to snake case; if null, default behavior is used
Return
An object representing the value of the instance
Declaration
bool $snakeCase = false
) : array
{
}
Description
Get the object value as an associative array
Parameters
Flag indicating whether to convert property names to snake case
Return
An associative array representing the object values
Declaration
{
}
Description
Get the object value as an associative array with the first letter of each key in upper camel case
Return
An associative array with keys in upper camel case
Declaration
{
}
Description
Check if the JSON naming strategy is snake case
Return
True if the naming strategy is snake case; otherwise, false
Declaration
{
}
Description
Check if the YAML naming strategy is snake case
Return
True if the naming strategy is snake case; otherwise, false
Declaration
{
}
Description
Check if the JSON naming strategy is upper camel case
Return
True if the naming strategy is upper camel case; otherwise, false
Declaration
{
}
Description
Check if the JSON naming strategy is camel case
Return
True if the naming strategy is camel case; otherwise, false
Declaration
{
}
Description
Check if the JSON output should be prettified
Return
True if JSON output is set to be prettified; otherwise, false
Declaration
mixed $params
) : bool
{
}
Description
Checks if the provided parameter is an array.
This function verifies if the given parameter is set and is of type array. It is a helper method used to validate the type of data before performing any operations on it that require an array.
Parameters
The parameter to check.
Return
Returns true if the parameter is set and is an array, otherwise returns false.
Declaration
mixed $value
) : bool
{
}
Description
Check if a value is not null and not empty
Parameters
The value to check
Return
True if the value is not null and not empty; otherwise, false
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array
{
}
Description
Get a list of properties
Parameters
Flag indicating whether to reflect properties of the current class
Flag indicating whether to return properties as an array
Return
An array of property names or ReflectionProperty objects
Declaration
PicoSpecification|null $specification = null,
PicoPageable|string|null $pageable = null,
PicoSortable|string|null $sortable = null,
bool $passive = false,
array|null $subqueryMap = null
) : PicoPageData
{
}
Description
List all records
Parameters
The specification for filtering
The pagination information
The sorting criteria
Flag indicating whether the object is passive
An optional map of subqueries
Return
The paginated data
Throws
if no records are found
if no database connection is established
Declaration
PicoDatabasePersistence $persist,
PicoSpecification|null $specification,
PicoPageable|string|null $pageable,
PicoSortable|string|null $sortable,
int $findOption = 0,
array|null $result = null
) : int
{
}
Description
Count the data based on specifications
Parameters
The persistence object
The specification for filtering
The pagination information
The sorting criteria
The find option
The result set
Return
The count of matching records
Declaration
PicoSpecification|null $specification = null,
PicoSortable|string|null $sortable = null,
array|null $subqueryMap = null
) : self
{
}
Description
Find one record based on specifications
Parameters
The specification for filtering
The sorting criteria
An optional map of subqueries
Return
The found instance.
Throws
if no record is found
if no database connection is established
Declaration
PicoSpecification|null $specification = null,
PicoPageable|string|null $pageable = null,
PicoSortable|string|null $sortable = null,
bool $passive = false,
array|null $subqueryMap = null,
int $findOption = 0
) : PicoPageData
{
}
Description
Find all records based on specifications
Parameters
The specification for filtering
The pagination information
The sorting criteria
Flag indicating whether the object is passive
An optional map of subqueries
The find option
Return
The paginated data
Throws
if no records are found
if no database connection is established
Declaration
{
}
Description
Find all records without filters, sorted by primary key in ascending order
Return
The paginated data
Declaration
{
}
Description
Find all records without filters, sorted by primary key in descending order
Return
The paginated data
Declaration
string $selected,
PicoSpecification|null $specification = null,
PicoPageable|string|null $pageable = null,
PicoSortable|string|null $sortable = null,
bool $passive = false,
array|null $subqueryMap = null,
int $findOption = 0
) : PicoPageData
{
}
Description
Find specific records
Parameters
The selected field(s)
The specification for filtering
The pagination information
The sorting criteria
Flag indicating whether the object is passive
An optional map of subqueries
The find option
Return
The paginated data
Throws
if no records are found
if no database connection is established
Declaration
PicoDatabasePersistence $persist,
PicoSpecification|null $specification,
PicoPageable|string|null $pageable,
PicoSortable|string|null $sortable,
int $findOption,
mixed $result
) : int
{
}
Description
Counts the total number of records for a given query, with special handling for SQLite.
Parameters
The persistence object to interact with the database.
The specification used to filter the results.
Pagination information.
Sorting information.
The find option flag indicating how the query should be executed.
The result set to count.
Return
The total number of matching records.
Declaration
PicoDatabasePersistence $persist,
PicoSpecification|null $specification,
PicoPageable|string|null $pageable,
PicoSortable|string|null $sortable,
int $findOption,
mixed $result
) : int
{
}
Description
Counts the total number of records for a given query with pagination, with special handling for SQLite.
Parameters
The persistence object to interact with the database.
The specification used to filter the results.
Pagination information.
Sorting information.
The find option flag indicating how the query should be executed.
The result set to count.
Return
The total number of matching records considering pagination.
Declaration
PicoSpecification|null $specification = null,
PicoPageable|null $pageable = null,
PicoSortable|null $sortable = null
) : int|false
{
}
Description
Count all records based on specifications
Parameters
The specification for filtering
The pagination information
The sorting criteria
Return
The count of records or false on error
Throws
if no records are found
if no database connection is established
Declaration
PicoSpecification|null $specification = null,
PicoPageable|string|null $pageable = null,
PicoSortable|string|null $sortable = null
) : PicoDatabaseQueryBuilder
{
}
Description
Build a query to find all records
Parameters
The specification for filtering
The pagination information
The sorting criteria
Return
The query builder
Throws
if no record is found
if no database connection is established
Declaration
mixed $params
) : self
{
}
Description
Find one record by primary key value
Parameters
The parameters for the search
Return
The found instance.
Throws
if no record is found
if no database connection is established
Declaration
array $params
) : self
{
}
Description
Find one record if it exists by primary key value
Parameters
The parameters for the search
Return
The found instance. or the current instance if not found
Declaration
string $method,
mixed $params,
PicoSpecification|null $specification,
PicoPageable|string|null $pageable = null,
PicoSortable|string|null $sortable = null,
bool $passive = false,
array|null $subqueryMap = null
) : PicoPageData
{
}
Description
Find records by specified parameters
Parameters
The method to find by
The parameters for the search
The specification for filtering
The pagination information
The sorting criteria
Flag indicating whether the object is passive
An optional map of subqueries
Return
The paginated data
Throws
if no records are found
if no database connection is established
Declaration
string $method,
mixed $params
) : int
{
}
Description
Count data from the database.
Parameters
The method used for finding.
The parameters to use for the count.
Return
The count of matching records.
Throws
If there is no database connection.
Declaration
string $method,
mixed $params
) : int
{
}
Description
Delete records based on parameters.
Parameters
The method used for finding.
The parameters to use for the deletion.
Return
The number of deleted records.
Throws
If there is no database connection.
Declaration
mixed $primaryKeyVal,
array|null $subqueryMap = null
) : self
{
}
Description
Find one record using the primary key value.
Parameters
The primary key value.
Optional subquery map for additional queries.
Return
The found instance.
Throws
If no record is found.
If there is no database connection.
Declaration
string $method,
mixed $params,
PicoSortable|string|null $sortable = null
) : object
{
}
Description
Find one record based on specified parameters.
Parameters
The method used for finding.
The parameters to use for the search.
Optional sorting criteria.
Return
The found instance.
Throws
If no record is found.
If there is no database connection.
Declaration
string $method,
mixed $params,
PicoSortable|string|null $sortable = null
) : object
{
}
Description
Find one record if it exists based on parameters.
Parameters
The method used for finding.
The parameters to use for the search.
Optional sorting criteria.
Return
The found instance or the current instance if not found.
Throws
If there is no database connection.
Declaration
string $method,
mixed $params
) : bool
{
}
Description
Delete one record based on specified parameters.
Parameters
The method used for finding.
The parameters to use for the deletion.
Return
True on success; otherwise, false.
Throws
If there is no database connection.
Declaration
string $method,
mixed $params
) : bool
{
}
Description
Check if a record exists based on specified parameters.
Parameters
The method used for finding.
The parameters to use for the search.
Return
True if the record exists; otherwise, false.
Throws
If there is no database connection.
Declaration
string $propertyName,
string[] $params
) : string
{
}
Description
Convert a boolean value to text based on the specified property name.
Parameters
The property name to check.
The text representations for true and false.
Return
The corresponding text representation.
Declaration
array $result,
bool $passive = false
) : array
{
}
Description
Convert the result to an array of objects.
Parameters
The result set to convert.
Flag indicating whether the objects are passive.
Return
An array of objects.
Declaration
{
}
Description
Get the number of properties of the object.
Return
The number of properties.
Declaration
string $method,
mixed $params
) : mixed|null
{
}
Description
Magic method called when a user calls any undefined method. The __call method checks the prefix of the called method and invokes the appropriate method according to its name and parameters.
Method Descriptions:
-
hasValue: Checks if the property has a value.
- Example:
$object->hasValuePropertyName();
- Example:
-
isset: Checks if the property is set.
- Example:
$object->issetPropertyName();
- Example:
-
is: Retrieves the property value as a boolean.
- Example:
$isActive = $object->isActive();
- Example:
-
equals: Checks if the property value equals the given value.
- Example:
$isEqual = $object->equalsPropertyName($value);
- Example:
-
get: Retrieves the property value.
- Example:
$value = $object->getPropertyName();
- Example:
-
set: Sets the property value.
- Example:
$object->setPropertyName($value);
- Example:
-
unset: Unsets the property value.
- Example:
$object->unsetPropertyName();
- Example:
-
push: Adds array elements to a property at the end.
- Example:
$object->pushPropertyName($newElement);
- Example:
-
append: Appends array elements to a property at the end.
- Example:
$object->appendPropertyName($newElement);
- Example:
-
unshift: Adds array elements to a property at the beginning.
- Example:
$object->unshiftPropertyName($newElement);
- Example:
-
prepend: Prepends array elements to a property at the beginning.
- Example:
$object->prependPropertyName($newElement);
- Example:
-
pop: Removes the last element from the property.
- Example:
$removedElement = $object->popPropertyName();
- Example:
-
shift: Removes the first element from the property.
- Example:
$removedElement = $object->shiftPropertyName();
- Example:
-
findOneBy: Searches for data in the database and returns one record.
- Example:
$record = $object->findOneByPropertyName($value); - Requires a database connection.
- Example:
-
findOneIfExistsBy: Searches for data in the database by any column values and returns one record.
- Example:
$record = $object->findOneIfExistsByPropertyName($value, $sortable); - Requires a database connection.
- Example:
-
deleteOneBy: Deletes data from the database by any column values and returns one record.
- Example:
$deletedRecord = $object->deleteOneByPropertyName($value, $sortable); - Requires a database connection.
- Example:
-
findFirstBy: Searches for data in the database by any column values and returns the first record.
- Example:
$firstRecord = $object->findFirstByColumnName($value); - Requires a database connection.
- Example:
-
findFirstIfExistsBy: Similar to
findFirstBy, but returns the first record if it exists.- Example:
$firstRecord = $object->findFirstIfExistsByPropertyName($value, $sortable); - Requires a database connection.
- Example:
-
findLastBy: Searches for data in the database by any column values and returns the last record.
- Example:
$lastRecord = $object->findLastByColumnName($value); - Requires a database connection.
- Example:
-
findLastIfExistsBy: Similar to
findLastBy, but returns the last record if it exists.- Example:
$lastRecord = $object->findLastIfExistsByPropertyName($value, $sortable); - Requires a database connection.
- Example:
-
findBy: Searches for multiple records in the database by any column values.
- Example:
$records = $object->findByColumnName($value); - Requires a database connection.
- Example:
-
countBy: Counts data from the database.
- Example:
$count = $object->countByColumnName();
- Example:
-
existsBy: Checks for data in the database.
- Example:
$exists = $object->existsByColumn($column); - Requires a database connection.
- Example:
-
deleteBy: Deletes data from the database without reading it first.
- Example:
$object->deleteByPropertyName($value); - Requires a database connection.
- Example:
-
booleanToTextBy: Converts a boolean value to "yes/no" or "true/false" based on given parameters.
- Example:
$result = $object->booleanToTextByActive("Yes", "No"); - If $obj->active is true, $result will be "Yes"; otherwise, it will be "No".
- Example:
-
startsWith: Checks if the value starts with a given string.
- Example:
$startsWith = $object->startsWithPropertyName("prefix");
- Example:
-
endsWith: Checks if the value ends with a given string.
- Example:
$endsWith = $object->endsWithPropertyName("suffix");
- Example:
-
label: Retrieves the label associated with the given property.
- If the label is not set, it attempts to fetch it from annotations.
- Example:
$label = $object->labelPropertyName();
-
option: Returns the first parameter if the property is set to
trueor equals1; otherwise returns the second parameter.- Example:
$option = $object->optionPropertyName("Yes", "No");
- Example:
-
notNull: Checks if the specified property is set (not null).
- Example:
$isNotNull = $object->notNullPropertyName();
- Example:
-
notEmpty: Checks if the specified property is set and not empty.
- Example:
$isNotEmpty = $object->notEmptyPropertyName();
- Example:
-
notZero: Checks if the specified property is set and not equal to zero.
- Example:
$isNotZero = $object->notZeroPropertyName();
- Example:
-
notEquals: Checks if the specified property is set and does not equal the given value.
- Example:
$isNotEqual = $object->notEqualsPropertyName($value);
- Example:
Parameters
Method name
Parameters for the method
Return
The result of the called method, or null if not applicable
Declaration
{
}
Description
Magic method to convert the object to a string.
Return
A JSON representation of the object.
Declaration
self $value,
bool $snake
) : mixed
{
}
Description
Recursively stringify an object or array of objects.
Parameters
The object to stringify.
Flag to indicate whether to convert property names to snake_case.
Return
The stringified object or array.
Declaration
int|null $inline = null,
int $indent = 4,
int $flags = 0
) : string
{
}
Description
Dumps a PHP value to a YAML string.
The dump method, when supplied with an array, converts it into a friendly YAML format.
Parameters
The level at which to switch to inline YAML. If NULL, the maximum depth will be used.
The number of spaces to use for indentation of nested nodes.
A bit field of DUMP_* constants to customize the dumped YAML string.
Return
A YAML string representing the original PHP value.
MagicObject\SecretObject
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
SecretObject class
This class provides mechanisms to manage properties that require encryption and decryption during their lifecycle. It uses annotations to specify which properties should be encrypted or decrypted when they are set or retrieved. These annotations help identify when to apply encryption or decryption, either before saving (SET) or before fetching (GET).
The class supports flexibility in data initialization, allowing data to be passed as an array, an object, or even left empty. Additionally, a secure callback function can be provided to handle key generation for encryption and decryption operations.
Key features:
- Encryption and decryption of object properties based on annotations.
- Support for customizing property naming strategies.
- Option to provide a secure function for key generation.
Constants
Properties
Declaration
Description
List of properties to be encrypted when calling SET.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Class parameters.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
NULL properties.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
List of properties to be decrypted when calling GET.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
List of properties to be encrypted when calling GET.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
List of properties to be decrypted when calling SET.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Indicates if the object is read-only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Secure function to get encryption key.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
self|array|object|null $data = null,
callable|null $secureCallback = null
)
{
}
Description
Constructor for initializing the object with data.
This constructor accepts initial data in various formats (array or object) and allows the optional specification of a callback function for secure key generation. The data is processed and loaded into the object upon instantiation.
Parameters
The initial data for the object. Can be an
An optional callback function for generating
Declaration
{
}
Description
Analyzes the class's parameters and properties to determine which should be encrypted or decrypted based on annotations.
This method uses reflection to retrieve the class's parameters and properties. It then parses annotations associated with these members to identify which properties should undergo encryption or decryption during specific stages (before storage or before retrieval). The appropriate lists of properties are populated accordingly.
Return
Throws
If the annotations are invalid or cannot be parsed.
Declaration
{
}
Description
Generates a secure key for encryption and decryption.
This method checks for a user-defined secure key generation function. If a valid function is provided, it calls that function to generate the key. Otherwise, it returns a concatenation of predefined random keys.
Return
The secure key for encryption/decryption.
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method called when invoking undefined methods.
This method handles dynamic method calls for property management.
Supported methods:
-
isset<PropertyName>: Checks if the property is set.- Example:
$obj->issetFoo()returns true if propertyfoois set.
- Example:
-
is<PropertyName>: Checks if the property is set and equals 1 (truthy).- Example:
$obj->isFoo()returns true if propertyfoois set and is equal to 1.
- Example:
-
get<PropertyName>: Retrieves the value of the property.- Example:
$value = $obj->getFoo()gets the value of propertyfoo.
- Example:
-
set<PropertyName>: Sets the value of the property.- Example:
$obj->setFoo($value)sets the propertyfooto$value.
- Example:
-
unset<PropertyName>: Unsets the property.- Example:
$obj->unsetFoo()removes the propertyfoo.
- Example:
-
push<PropertyName>: Pushes a value onto an array property.- Example:
$obj->pushFoo($value)adds$valueto the array propertyfoo.
- Example:
-
pop<PropertyName>: Pops a value from an array property.- Example:
$value = $obj->popFoo()removes and returns the last value from the array propertyfoo.
- Example:
Parameters
Method name.
Parameters for the method.
Return
The result of the method call or null if not applicable.
Declaration
string $var,
mixed $value
) : self
{
}
Description
Set a value for the specified property.
This method sets the value of a property and applies encryption or decryption if necessary based on the defined property rules.
Parameters
The name of the property.
The value to set.
Return
Returns the current instance for method chaining.
Declaration
string $var
) : mixed
{
}
Description
Get the value of the specified property.
This method retrieves the value of a property and applies encryption or decryption if necessary based on the defined property rules.
Parameters
The name of the property.
Return
The value of the property.
Declaration
string $var
) : mixed
{
}
Description
Get the raw value of the specified property.
This method retrieves the raw value of a property without any encryption or decryption.
Parameters
The name of the property.
Return
The raw value of the property, or null if not set.
Declaration
mixed $data
) : bool
{
}
Description
Check if the given data is an instance of MagicObject or PicoGenericObject.
Parameters
The data to check.
Return
True if the data is an instance, otherwise false.
Declaration
mixed $data
) : bool
{
}
Description
Check if the given data is an instance of self or stdClass.
Parameters
The data to check.
Return
True if the data is an instance, otherwise false.
Declaration
MagicObject|PicoGenericObject|self|array|stdClass|string|number $data,
string|null $hexKey = null
) : mixed
{
}
Description
Encrypt data recursively.
This method encrypts the provided data, which can be an object, array, or scalar value. It handles nested structures by encrypting each value individually.
Parameters
The data to encrypt.
The encryption key in hexadecimal format. If null, a secure key will be generated.
Return
The encrypted data.
Declaration
string $plaintext,
string|null $hexKey = null
) : string
{
}
Description
Encrypt a string.
This method encrypts a plain text string using a specified or generated secure key.
Parameters
The plain text to be encrypted.
The key in hexadecimal format. If null, a secure key will be generated.
Return
The encrypted string in base64 format.
Declaration
MagicObject|PicoGenericObject|self|array|stdClass|string $data,
string|null $hexKey = null
) : string|null
{
}
Description
Decrypt data recursively.
This method decrypts the provided ciphertext, which can be an object, array, or scalar value. It handles nested structures by decrypting each value individually.
Parameters
The ciphertext to decrypt.
The key in hexadecimal format. If null, a secure key will be generated.
Return
The decrypted string or null if decryption fails.
Declaration
string $ciphertext,
string|null $hexKey = null
) : string|null
{
}
Description
Decrypt a string.
This method decrypts a given ciphertext string using a specified or generated secure key.
Parameters
The encrypted data to be decrypted.
The key in hexadecimal format. If null, a secure key will be generated.
Return
The decrypted string or null if decryption fails.
Declaration
string $var
) : bool
{
}
Description
Check if a value requires encryption before being stored.
Parameters
The variable name.
Return
True if the value needs to be encrypted, otherwise false.
Declaration
string $var
) : bool
{
}
Description
Check if a value requires decryption after being read.
Parameters
The variable name.
Return
True if the value needs to be decrypted, otherwise false.
Declaration
string $var
) : bool
{
}
Description
Check if a value requires encryption after being read.
Parameters
The variable name.
Return
True if the value needs to be encrypted, otherwise false.
Declaration
string $var
) : bool
{
}
Description
Check if a value requires decryption before being stored.
Parameters
The variable name.
Return
True if the value needs to be decrypted, otherwise false.
Declaration
mixed $data
) : self
{
}
Description
Load data into the object.
This method populates the object's properties from the provided data, which can be an object, array, or scalar value.
Parameters
The data to load.
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false
) : self
{
}
Description
Load data from an INI string.
This method parses an INI formatted string and loads the data into the object.
Parameters
The raw INI data as a string.
Flag to indicate whether to use environment variable replacement.
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false
) : self
{
}
Description
Load data from an INI file.
This method reads an INI file and loads the data into the object.
Parameters
The path to the INI file.
Flag to indicate whether to use environment variable replacement.
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Load data from a YAML string.
This method parses a YAML formatted string and loads the data into the object.
Parameters
The YAML data as a string.
Flag to indicate whether to replace environment variables.
Flag to indicate whether to return results as an object.
Flag to indicate whether to convert nested objects to MagicObject.
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false,
bool $asObject = false,
bool $recursive = false
) : self
{
}
Description
Load data from a YAML file.
This method reads a YAML file and loads the data into the object.
Parameters
The path to the YAML file.
Flag to indicate whether to replace environment variables.
Flag to indicate whether to return results as an object.
Flag to indicate whether to convert nested objects to MagicObject.
Return
Returns the current instance for method chaining.
Declaration
string $rawData,
bool $systemEnv = false,
bool $recursive = false
) : self
{
}
Description
Load data from a JSON string.
This method parses a JSON formatted string and loads the data into the object.
Parameters
The JSON data as a string.
Flag to indicate whether to replace environment variables.
Flag to create recursive object.
Return
Returns the current instance for method chaining.
Declaration
string $path,
bool $systemEnv = false,
bool $recursive = false
) : self
{
}
Description
Load data from a JSON file.
This method reads a JSON file and loads the data into the object.
Parameters
The path to the JSON file.
Flag to indicate whether to replace environment variables.
Flag to create recursive object.
Return
Returns the current instance for method chaining.
Declaration
bool $readonly
) : self
{
}
Description
Set the object to read-only mode.
When in read-only mode, setters will not change the value of the object's properties, but the loadData method will still work.
Parameters
Flag to set the object to read-only.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed|null $propertyValue
) : self
{
}
Description
Set a property value.
Parameters
The name of the property to set.
The value to set for the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Add an element to a property array.
Parameters
The name of the property.
The value to add.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Remove the last element from a property array.
Parameters
The name of the property.
Return
The removed value or null if the property is not an array.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get a property value.
Parameters
The name of the property.
Return
The value of the property or null if not set.
Declaration
string $propertyName,
mixed|null $defaultValue = null
) : mixed
{
}
Description
Get a property value or return a default value if not set.
Parameters
The name of the property.
The default value to return if the property is not set.
Return
The property value or the default value.
Declaration
self|mixed $source,
array|null $filter = null,
bool $includeNull = false
) : self
{
}
Description
Copies values from another object to the current object based on specified filters.
This method allows selective copying of property values from a source object to the current object. You can specify which properties to copy using a filter, and you can choose whether to include properties with null values.
Parameters
The source object from which to copy values.
An optional array of property names to filter which values
A flag indicating whether to include properties with null
Return
Returns the current instance for method chaining.
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get object value.
This method retrieves the values of the object's properties, optionally converting the property names to snake case.
Parameters
Flag to convert property names to snake case.
Return
An object containing the values of the properties.
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get object value as an object.
This method is an alias for the value() method, allowing for retrieval of object values, optionally in snake case.
Parameters
Flag to convert property names to snake case.
Return
An object containing the values of the properties.
Declaration
bool $snakeCase = false
) : array
{
}
Description
Get object value as an associative array.
This method retrieves the object values and converts them to an associative array, optionally converting property names to snake case.
Parameters
Flag to convert property names to snake case.
Return
An associative array containing the values of the properties.
Declaration
{
}
Description
Get object value as an associative array with upper camel case keys.
This method retrieves the object values and converts them to an associative array, with keys formatted in upper camel case.
Return
An associative array containing the values of the properties with upper camel case keys.
Declaration
{
}
Description
Check if JSON naming strategy is snake case.
Return
True if the naming strategy is snake case, otherwise false.
Declaration
{
}
Description
Check if YAML naming strategy is snake case.
Return
True if the naming strategy is snake case, otherwise false.
Declaration
{
}
Description
Check if JSON naming strategy is upper camel case.
Return
True if the naming strategy is upper camel case, otherwise false.
Declaration
{
}
Description
Check if the JSON output should be prettified
Return
True if JSON output is set to be prettified; otherwise, false
Declaration
{
}
Description
Check if JSON naming strategy is camel case.
Return
True if the naming strategy is camel case, otherwise false.
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array
{
}
Description
Get the list of properties of the class.
This method returns an array of properties defined in the class, optionally reflecting the self class or converting the properties to an array.
Parameters
Flag to include properties defined in the current class.
Flag to return properties as an array.
Return
An array of ReflectionProperty objects or property names.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Modify null properties.
This method keeps track of properties that have been set to null, allowing for tracking changes to properties.
Parameters
The name of the property.
The value of the property.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the encrypted value of the object.
This method returns an array representation of the object's encrypted values.
Return
An array containing the encrypted values.
Declaration
array $array
) : array
{
}
Description
Encrypt values recursively.
This method encrypts each string value in the provided array. Nested arrays are also processed.
Parameters
The array of values to be encrypted.
Return
The array with encrypted values.
Declaration
int|null $inline = null,
int $indent = 4,
int $flags = 0
) : string
{
}
Description
Dumps a PHP value to a YAML string.
This method attempts to convert an array into a friendly YAML format.
Parameters
The level where to switch to inline YAML. If set to NULL,
The number of spaces to use for indentation of nested nodes.
A bit field of DUMP_* constants to customize the dumped YAML string.
Return
A YAML string representing the original PHP value.
Declaration
{
}
Description
Magic method to convert the object to a string.
This method returns a JSON representation of the object.
Return
A JSON representation of the object.
MagicObject\SetterGetter
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class SetterGetter
A dynamic object that provides getter and setter methods for properties, allowing flexible management of property values and array-like behavior. Supports annotations for property configuration and JSON serialization.
Constants
Properties
Declaration
Description
Class parameter storage.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
self|array|stdClass|object|null $data = null
)
{
}
Description
Constructor.
Initializes the object with data and parses class annotations for property configuration.
Parameters
Initial data for the object.
Declaration
mixed $data
) : self
{
}
Description
Load data into the object.
Maps the given data to the object's properties, automatically camelizing keys.
Parameters
Data to load, which can be another SetterGetter instance,
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed|null $propertyValue
) : self
{
}
Description
Set a property value.
Parameters
Name of the property to set.
Value to assign to the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Add an element to an array property.
Initializes the property as an array if it is not already set.
Parameters
Name of the property to push to.
Value to add to the property array.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Remove the last element from an array property.
Parameters
Name of the property to pop from.
Return
Returns the removed value or null if the property is not an array.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get a property value.
Parameters
Name of the property to retrieve.
Return
Returns the property value or null if not set.
Declaration
string $name,
mixed $value
) : void
{
}
Description
Magic setter method.
Enables setting properties using object syntax, e.g., $instance->foo = 'bar';.
Parameters
Name of the property to set.
Value to assign to the property.
Return
Declaration
string $name
) : mixed|null
{
}
Description
Magic getter method.
Enables retrieving properties using object syntax, e.g., echo $instance->foo;.
Parameters
Name of the property to retrieve.
Return
Returns the value of the property or null if not set.
Declaration
string $name
) : bool
{
}
Description
Check if a property is set.
Parameters
Name of the property to check.
Return
Returns true if the property is set, false otherwise.
Declaration
bool $snakeCase
) : stdClass
{
}
Description
Get values of the properties.
Optionally converts property names to snake_case for the returned object.
Parameters
Flag to determine if property names should be converted to snake_case.
Return
Returns an object with property values.
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get values of the properties.
Optionally converts property names to snake_case for the returned object.
Parameters
Flag to determine if property names should be converted to snake_case.
Return
Returns an object with property values.
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array|ReflectionProperty[]
{
}
Description
Get a list of properties.
Parameters
Flag to determine if only properties of the current class should be included.
Flag to convert the properties to an array.
Return
Returns an array of ReflectionProperty objects or property names based on $asArrayProps.
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method called when invoking undefined methods.
This method dynamically handles method calls for property management.
Supported dynamic methods:
-
isset<PropertyName>: Checks if the specified property is set.- Returns true if the property exists and is not null.
- Example:
$obj->issetFoo()checks if the propertyfoois set.
-
is<PropertyName>: Checks if the specified property is set and equals 1 (truthy).- Returns true if the property exists and its value is equal to 1.
- Example:
$obj->isFoo()checks iffoois set to 1.
-
get<PropertyName>: Retrieves the value of the specified property.- Returns the property value or null if it doesn't exist.
- Example:
$value = $obj->getFoo()gets the value of propertyfoo.
-
set<PropertyName>: Sets the value of the specified property.- Accepts a single parameter which is the value to be assigned to the property.
- Example:
$obj->setFoo($value)sets the propertyfooto$value.
-
unset<PropertyName>: Removes the specified property from the object.- Example:
$obj->unsetFoo()deletes the propertyfoo.
- Example:
-
push<PropertyName>: Pushes a value onto an array property.- If the property is not already an array, it initializes it as an empty array.
- Example:
$obj->pushFoo($value)adds$valueto the array propertyfoo.
-
pop<PropertyName>: Pops a value from an array property.- Returns the last value from the array property or null if it doesn't exist.
- Example:
$value = $obj->popFoo()removes and returns the last value from the array propertyfoo.
Parameters
Method name that was called.
Parameters passed to the method.
Return
The result of the method call or null if the method does not return a value.
Declaration
{
}
Description
Check if the JSON naming strategy is snake case.
Return
True if the naming strategy is snake case, false otherwise.
Declaration
{
}
Description
Check if the JSON naming strategy is camel case.
Return
True if the naming strategy is camel case, false otherwise.
Declaration
{
}
Description
Check if the JSON should be prettified.
Return
True if prettification is enabled, false otherwise.
Declaration
{
}
Description
Convert the object to a JSON string representation.
This method serializes the object to JSON format, with options for pretty printing based on the configuration. It uses the appropriate naming strategy for properties as specified in the class parameters.
Return
The JSON string representation of the object.
MagicObject\Txt
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class Txt
A utility class that provides dynamic handling of static method calls and dynamic property access. This class allows for flexible interaction by returning the names of methods and properties that are called statically or accessed dynamically but are not explicitly defined within the class. It can be useful for implementing dynamic behavior or creating a fluent interface.
Example
<?php
echo Txt::planetbiru(); // Will print "planetbiru"
echo Txt::of()->planetbiru; // Will print "planetbiru"
echo Txt::getInstance()->planetbiru; // Will print "planetbiru"
Methods
Declaration
string $name,
array $arguments
) : string
{
}
Description
Handles static calls to undefined methods.
This method intercepts calls to static methods that are not explicitly defined in the class and returns the name of the method being called. It allows for flexible handling of undefined static methods.
Parameters
The name of the method being called.
An array of arguments passed to the method.
Return
The name of the called method.
Declaration
{
}
Description
Returns a new instance of the Txt class.
This method allows you to retrieve an instance of the Txt class for non-static operations.
This instance can be used to access dynamic properties via the __get() magic method.
Return
A new instance of the Txt class.
Declaration
{
}
Description
Creates and returns a new instance of the Txt class.
Similar to getInstance(), this method allows you to retrieve an instance of the Txt class
for non-static operations, such as dynamic property access using the __get() magic method.
Return
A new instance of the Txt class.
Declaration
string $name
) : string
{
}
Description
Handles dynamic access to undefined properties.
This method is invoked when an undefined property is accessed on an instance of the Txt class. It returns the name of the property being accessed.
Parameters
The name of the property being accessed.
Return
The name of the accessed property.
MagicObject\ComplexNumber\ComplexNumber
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
ComplexNumber class
Properties
Declaration
Description
Real part of the complex number.
Declaration
Description
Imaginary part of the complex number.
Methods
Declaration
float $real,
float $imaginary
)
{
}
Description
Constructor to initialize the complex number.
Parameters
Real part of the complex number.
Imaginary part of the complex number.
Declaration
self $self
) : self
{
}
Description
Add another complex number to this one.
Parameters
The complex number to add.
Return
The sum of the two complex numbers.
Declaration
self $self
) : self
{
}
Description
Subtract another complex number from this one.
Parameters
The complex number to subtract.
Return
The result of the subtraction.
Declaration
self $self
) : self
{
}
Description
Multiply this complex number by another.
Parameters
The complex number to multiply.
Return
The product of the two complex numbers.
Declaration
self $self
) : self
{
}
Description
Divide this complex number by another.
Parameters
The complex number to divide by.
Return
The result of the division.
Declaration
{
}
Description
Get the magnitude of the complex number.
Return
The magnitude of the complex number.
Declaration
{
}
Description
Get the conjugate of the complex number.
Return
The conjugate of the complex number.
Declaration
{
}
Description
String representation of the complex number.
Return
The complex number as a string.
Declaration
{
}
Description
Get the real part of the complex number.
Return
The real part.
Declaration
float $real
) : self
{
}
Description
Set the real part of the complex number.
Parameters
The real part.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the imaginary part of the complex number.
Return
The imaginary part.
Declaration
float $imaginary
) : self
{
}
Description
Set the imaginary part of the complex number.
Parameters
The imaginary part.
Return
Returns the current instance for method chaining.
MagicObject\Constants\PicoHttpStatus
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoHttpStatus
This class defines constants for standard HTTP status codes.
Constants
Properties
Declaration
Description
HTTP status codes and their respective messages.
This array holds the standard HTTP status codes along with their descriptions. It can be used to provide meaningful responses in HTTP communication.
MagicObject\Constants\PicoMime
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoMime
This class contains constants representing various MIME types.
Constants
MagicObject\Constants\PicoMimeMap
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoMimeMap
This class defines a mapping of file extensions to their corresponding MIME types. It can be used to determine the appropriate content type for files based on their extensions.
Constants
Methods
Declaration
string $extension
) : string
{
}
Description
Loock up mime type
Parameters
Extension
Return
Declaration
string $mimetype
) : string
{
}
Description
Look up extension
Parameters
MIME Type
Return
Declaration
string $mimetype
) : string[]
{
}
Description
Look up all extensions
Parameters
MIME Type
Return
MagicObject\Database\PicoDatabase
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
PicoDatabase provides an interface for database interactions using PDO.
This class manages database connections, query execution, and transactions. It supports callbacks for query execution and debugging, allowing developers to handle SQL commands and responses effectively.
Features include:
- Establishing and managing a database connection.
- Executing various SQL commands (INSERT, UPDATE, DELETE, etc.).
- Transaction management with commit and rollback functionality.
- Fetching results in different formats (array, object, etc.).
-
Generating unique IDs and retrieving the last inserted ID.
Example:
<?php $db = new PicoDatabase($credentials); $db->connect(); $result = $db->fetch("SELECT * FROM users WHERE id = 1");
Constants
Properties
Declaration
Description
Database credential.
Declaration
Description
Indicates whether the database is connected or not.
Declaration
Description
Autocommit setting.
Declaration
Description
Database connection.
Declaration
Description
Database type.
Declaration
Description
Callback function when executing queries that modify data.
Declaration
Description
Callback function when executing any query.
Methods
Declaration
PDO $pdo
) : PicoDatabase
{
}
Description
Creates a PicoDatabase instance from an existing PDO connection.
This static method accepts a PDO connection object, initializes a new PicoDatabase instance, and sets up the database connection and type. It also marks the database as connected and returns the configured PicoDatabase object.
Parameters
The PDO connection object representing an active connection to the database.
Return
Returns a new instance of the PicoDatabase class,
Declaration
PDO $pdo,
string $driver,
string $dbType
) : SecretObject
{
}
Description
Retrieves detailed information about a PDO database connection.
This method extracts and organizes connection details, including:
- Database driver (e.g., 'mysql', 'pgsql', 'sqlite').
- Host and port (if available).
- Database name (derived from the connection DSN).
- Schema (for applicable databases like PostgreSQL).
-
Time zone (calculated from the database offset or default PHP time zone).
The extraction process dynamically adapts to the type of database (e.g., MySQL, PostgreSQL, SQLite). For PostgreSQL, the schema is determined using a database query. Time zone information is calculated by converting the database offset to a corresponding PHP time zone where possible.
The resulting connection details are encapsulated in a
SecretObjectfor secure handling and organized access.
Parameters
The PDO connection object.
The name of the database driver (e.g., 'mysql', 'pgsql', 'sqlite').
The database type constant as defined in PicoDatabaseType.
Return
A SecretObject instance containing the following properties:
Throws
If an error occurs during database interaction, such as a query failure or
Declaration
PDO $pdo
) : string
{
}
Description
Retrieves the timezone offset from the database.
This function detects the database type (MySQL, MariaDB, or PostgreSQL) from the given PDO connection and executes the appropriate query to determine the timezone offset from UTC. It returns the offset as a string in the format "+HH:MM" or "-HH:MM". If the database type is unsupported or an error occurs, it defaults to "00:00".
Parameters
The PDO connection object.
Return
The timezone offset as a string (e.g., "+08:00", "-05:30"), or "00:00" on failure.
Declaration
string $offset
) : string
{
}
Description
Converts a timezone offset string to a corresponding PHP timezone name.
This method takes a timezone offset string (e.g., "+08:00" or "-05:30") and computes the total offset in seconds. It then attempts to map the offset to a standard PHP timezone name. If no matching timezone is found, it falls back to returning a UTC-based timezone string in the same offset format.
Examples:
- Input: "+07:00" -> Output: "Asia/Jakarta" (if mapping exists).
- Input: "-05:30" -> Output: "UTC-05:30" (fallback if no mapping exists).
Parameters
The timezone offset string (e.g., "+07:00", "-05:30").
Return
The corresponding PHP timezone name, or a fallback UTC offset string (e.g., "UTC+07:00").
Declaration
SecretObject $databaseCredentials,
callable|null $callbackExecuteQuery = null,
callable|null $callbackDebugQuery = null
)
{
}
Description
Constructor to initialize the PicoDatabase object.
Parameters
Database credentials.
Callback for executing modifying queries. Parameter 1 is SQL, parameter 2 is one of query type (PicoDatabase::QUERY_INSERT, PicoDatabase::QUERY_UPDATE, PicoDatabase::QUERY_DELETE, PicoDatabase::QUERY_TRANSACTION).
Callback for debugging queries. Parameter 1 is SQL.
Declaration
bool $withDatabase = true
) : bool
{
}
Description
Connect to the database.
Establishes a connection to the specified database type. Optionally selects a database if the connection is to an RDMS and the flag is set.
Parameters
Flag to select the database when connected (default is true).
Return
True if the connection is successful, false if it fails.
Declaration
{
}
Description
Connect to SQLite database.
Establishes a connection to an SQLite database using the specified file path in the credentials. Throws an exception if the database path is not set or is empty.
Return
True if the connection is successful, false if it fails.
Throws
If the database path is empty.
If the connection fails with an error.
Declaration
bool $withDatabase = true
) : bool
{
}
Description
Connect to the RDMS (Relational Database Management System).
Establishes a connection to an RDMS database using the provided credentials. Optionally, a specific database is selected based on the provided flag. This method also configures the time zone, character set, and schema settings (for PostgreSQL) after the connection is established.
- The time zone is set based on the current offset (
date("P")), or a configured value. - For PostgreSQL, the client encoding (charset) is set using
SET CLIENT_ENCODING, and the schema is set usingSET search_path. - For MySQL, the time zone and charset are set using
SET time_zoneandSET NAMES.
Parameters
Flag to specify whether to select a database upon connection (default is true).
Return
True if the connection is successfully established, false otherwise.
Throws
If the database username is missing from the configuration.
If an error occurs during the connection process.
Declaration
string $connectionString,
string $timeZoneOffset,
string $charset
) : void
{
}
Description
Establish a connection to a MySQL or MariaDB database.
This method sets up a connection to a MySQL or MariaDB database, configuring the time zone and character set (charset) as needed. It runs initial queries to set the correct time zone and charset, and then establishes a PDO connection to the database.
Parameters
The connection string used to connect to the database.
The time zone offset to be used in the database session.
The character set (charset) to be used for the database connection.
Return
Throws
If there is an error while establishing the connection or executing the initial queries.
Declaration
string $connectionString,
string $timeZoneOffset,
string $charset
) : void
{
}
Description
Establish a connection to a PostgreSQL database.
This method sets up a connection to a PostgreSQL database, configuring the time zone, character set (charset), and schema (search path) as needed. It runs initial queries to set the correct time zone, charset, and schema for the session, and then establishes a PDO connection to the database.
Parameters
The connection string used to connect to the PostgreSQL database.
The time zone offset to be used in the database session.
The character set (charset) to be used for the PostgreSQL connection.
Return
Throws
If there is an error while establishing the connection or executing the initial queries.
Declaration
string $connectionString
) : void
{
}
Description
Establish a connection to a SQL Server database.
This method sets up a connection to a SQL Server database and then establishes a PDO connection to the database.
Parameters
The connection string used to connect to the SQL Server database.
Return
Throws
If there is an error while establishing the connection or executing the initial queries.
Declaration
string $databaseType
) : string
{
}
Description
Determine the database type from a string.
This method evaluates the provided string to identify common database types such as SQLite, PostgreSQL,
MariaDB, MySQL, and SQL Server. It returns the corresponding constant from the PicoDatabaseType class.
If the provided database type is not supported, it throws an UnsupportedDatabaseException.
Parameters
The database type string (e.g., 'SQLite', 'PostgreSQL', 'MariaDB', 'MySQL', 'SQLServer').
Return
The corresponding PicoDatabaseType constant, one of:
Throws
If the database type is unsupported.
Declaration
string $databaseType
) : string
{
}
Description
Determines the database driver based on the provided database type.
This function takes a string representing the database type and returns
the corresponding database driver constant from the PicoDatabaseType class.
It supports SQLite, PostgreSQL, MySQL/MariaDB, and SQL Server types.
Parameters
The type of the database (e.g., 'sqlite', 'postgres', 'pgsql', 'mysql', 'mariadb', 'sqlsrv').
Return
The corresponding database driver constant, one of:
Declaration
bool $withDatabase = true
) : string
{
}
Description
Create a connection string.
Parameters
Flag to select the database when connected.
Return
The constructed connection string.
Throws
If database configuration is invalid.
Declaration
{
}
Description
Disconnect from the database.
This method sets the database connection to null, effectively closing the connection to the database.
Return
Returns the current instance for method chaining.
Declaration
string $timeZoneOffset
) : self
{
}
Description
Set the time zone offset for the database session.
This method sets the time zone offset for the current session, which can be useful for time-related operations.
Parameters
The time zone offset to set for the session (e.g., '+00:00', 'Europe/London').
Return
Returns the current instance for method chaining.
Declaration
string $timeZoneOffset
) : self
{
}
Description
Set the time zone offset for the database session.
This method sets the time zone offset for the current database session. This is useful for ensuring that any time-related operations (such as querying and storing timestamps) are adjusted to the correct time zone. The method generates the appropriate SQL command based on the type of the database (e.g., PostgreSQL, MySQL, etc.) and executes it to apply the time zone setting.
Parameters
The time zone offset to set for the session. It can either be a valid UTC offset (e.g., '+00:00')
Return
Returns the current instance for method chaining.
Declaration
string $timezone
) : string
{
}
Description
Converts a timezone name (e.g., 'Asia/Jakarta') to its corresponding UTC offset (e.g., '+07:00' or '-03:00').
This function will return the timezone offset without affecting the current PHP runtime timezone.
Parameters
The name of the timezone, e.g., 'Asia/Jakarta'.
Return
The UTC offset corresponding to the provided timezone, e.g., '+07:00' or '-03:00'.
Declaration
string $databaseName
) : self
{
}
Description
Switch to a different database.
This method changes the currently active database to the specified one.
Parameters
The name of the database to switch to.
Return
Returns the current instance for method chaining.
Declaration
bool $autocommit
) : bool
{
}
Description
Set autocommit mode for transactions.
This method enables or disables autocommit mode for database transactions. When autocommit is off,
you must explicitly call commit() or rollback() to finalize or revert the transaction.
Parameters
Flag indicating whether autocommit should be enabled (true) or disabled (false).
Return
Returns true if the autocommit setting was successfully updated, false otherwise.
Declaration
{
}
Description
Start a new database transaction.
This method begins a new transaction, allowing subsequent database operations to be grouped together. The changes made during the transaction are not permanent until the transaction is committed.
Return
Returns true if the transaction was successfully started, false otherwise.
Declaration
{
}
Description
Commit the current transaction.
This method commits the transaction, making all changes made during the transaction permanent.
Return
Returns true if the transaction was successfully committed, false otherwise.
Declaration
{
}
Description
Rollback the current transaction.
This method rolls back the transaction, undoing any changes made during the transaction.
Return
Returns true if the transaction was successfully rolled back, false otherwise.
Declaration
{
}
Description
Get the current database connection.
This method returns the active PDO connection object, which can be used for executing queries directly.
Return
The active PDO connection object representing the connection to the database server.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute a SQL query.
This method executes a SQL query with optional parameters and returns the resulting PDO statement object.
Parameters
The SQL query to execute.
Optional parameters to bind to the query.
Return
Returns a PDOStatement object if the query was executed successfully,
Throws
If an error occurs while executing the query.
Declaration
string $sql,
int $tentativeType = 2,
mixed $defaultValue = null,
array|null $params = null
) : array|object|stdClass|null
{
}
Description
Fetch a result from the database.
This method executes a query and returns a single result. If no result is found, the default value is returned.
Parameters
SQL query to be executed.
The fetch mode to be used (e.g., PDO::FETCH_ASSOC).
The default value to return if no results are found.
Optional parameters to bind to the SQL query.
Return
Returns the fetched result (array, object, or stdClass), or the default value if no results are found.
Declaration
string $sql,
array|null $params = null
) : bool
{
}
Description
Check if a record exists in the database.
This method executes a query and checks if any record is returned.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns true if the record exists, false otherwise.
Throws
If the database connection is null.
Declaration
string $sql,
int $tentativeType = 2,
mixed $defaultValue = null,
array|null $params = null
) : array|null
{
}
Description
Fetch all results from the database.
This method executes a query and returns all matching results. If no results are found, the default value is returned.
Parameters
SQL query to be executed.
The fetch mode to be used (e.g., PDO::FETCH_ASSOC).
The default value to return if no results are found.
Optional parameters to bind to the SQL query.
Return
Returns an array of results or the default value if no results are found.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute a SQL query without returning any results.
This method executes a query without expecting any result, typically used for non-SELECT queries (INSERT, UPDATE, DELETE).
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Throws
If the database connection is null.
If an error occurs while executing the query.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute a SQL query and return the statement object.
This method executes a query and returns the PDOStatement object, which can be used to fetch results or retrieve row count.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Throws
If the database connection is null.
If an error occurs while executing the query.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute an insert query and return the statement.
This method executes an insert query and returns the PDOStatement object.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute an update query and return the statement.
This method executes an update query and returns the PDOStatement object.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute a delete query and return the statement.
This method executes a delete query and returns the PDOStatement object.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Declaration
string $sql,
array|null $params = null
) : PDOStatement|false
{
}
Description
Execute a transaction query and return the statement.
This method executes a query as part of a transaction and returns the PDOStatement object.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Return
Returns the PDOStatement object if successful, or false on failure.
Declaration
string $query,
array|null $params = null,
string|null $type = null
)
{
}
Description
Execute a callback query function after executing the query.
This method calls the provided callback function after executing a query.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Type of the query (e.g., INSERT, UPDATE, DELETE, etc.).
Declaration
string $query,
array|null $params = null
)
{
}
Description
Execute a debug query function.
This method calls a debug callback function if it is set.
Parameters
SQL query to be executed.
Optional parameters to bind to the SQL query.
Declaration
{
}
Description
Generate a unique 20-byte ID.
This method generates a unique ID by concatenating a 13-character string
from uniqid() with a 6-character random hexadecimal string, ensuring
the resulting string is 20 characters in length.
Return
A unique 20-byte identifier.
Declaration
string|null $name = null
) : string|false
{
}
Description
Get the last inserted ID.
This method retrieves the ID of the last inserted record. Optionally, you can provide a sequence name (e.g., for PostgreSQL) to fetch the last inserted ID from a specific sequence.
Parameters
The sequence name (e.g., PostgreSQL). Default is null.
Return
Returns the last inserted ID as a string, or false if there was an error.
Declaration
{
}
Description
Get the value of database credentials.
This method returns the object containing the database credentials used to establish the database connection.
Return
The database credentials object.
Declaration
{
}
Description
Check whether the database is connected.
This method returns a boolean value indicating whether the database connection is currently active.
Return
Returns true if connected, false otherwise.
Declaration
{
}
Description
Get the type of the database.
This method returns the type of the database that is currently connected.
The possible values are constants from the PicoDatabaseType class:
PicoDatabaseType::DATABASE_TYPE_MYSQLPicoDatabaseType::DATABASE_TYPE_MARIADBPicoDatabaseType::DATABASE_TYPE_PGSQLPicoDatabaseType::DATABASE_TYPE_SQLITE
Return
The type of the database.
Declaration
{
}
Description
Retrieves the time zone used by the database.
This function calls the getTimeZone() method from the databaseCredentials
object to fetch the time zone configured for the database connection.
Return
The time zone of the database (e.g., "UTC", "America/New_York").
Declaration
{
}
Description
Retrieves the time zone offset of the database connection.
This function retrieves the time zone offset by calling the static method
getTimeZoneOffset() with the databaseConnection as an argument.
The offset is returned in seconds from UTC.
Return
The time zone offset, typically in hours and minutes (e.g., "+02:00").
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
Declaration
{
}
Description
Get the callback function to be executed when modifying data with queries.
This function returns the callback that is invoked when executing queries
that modify data (e.g., INSERT, UPDATE, DELETE).
Return
The callback function, or null if no callback is set.
Declaration
callable|null $callbackExecuteQuery
) : self
{
}
Description
Set the callback function to be executed when modifying data with queries.
This method sets the callback to be invoked when executing queries
that modify data (e.g., INSERT, UPDATE, DELETE).
Parameters
The callback function to set, or null to unset the callback.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the callback function to be executed when executing any query.
This function returns the callback that is invoked for any type of query,
whether it's a read (SELECT) or modify (INSERT, UPDATE, DELETE).
Return
The callback function, or null if no callback is set.
Declaration
callable|null $callbackDebugQuery
) : self
{
}
Description
Set the callback function to be executed when executing any query.
This method sets the callback to be invoked for any type of query,
whether it's a read (SELECT) or modify (INSERT, UPDATE, DELETE).
Parameters
The callback function to set, or null to unset the callback.
Return
Returns the current instance for method chaining.
MagicObject\Database\PicoDatabaseCredentials
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
PicoDatabaseCredentials class
This class encapsulates database credentials and utilizes the SecretObject to encrypt all attributes, ensuring the security of database configuration details from unauthorized access.
It provides getter methods to retrieve database connection parameters such as driver, host, port, username, password, database name, schema, and application time zone.
Example usage:
<?php
$credentials = new PicoDatabaseCredentials();
$credentials->setHost('localhost');
$credentials->setUsername('user');
$credentials->setPassword('password');
The attributes are automatically encrypted when set, providing a secure way to handle sensitive information within your application.
Properties
Declaration
Description
Database driver (e.g., 'mysql', 'pgsql', 'mariadb', 'sqlite').
Declaration
Description
Database file path for SQLite.
Declaration
Description
Database server host.
Declaration
Description
Database server port.
Declaration
Description
Database username.
Declaration
Description
Database user password.
Declaration
Description
Database name.
Declaration
Description
Database schema (default: 'public').
Declaration
Description
Application time zone.
Declaration
Description
Charset
Declaration
Description
Class parameters.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
NULL properties.
The property name starts with an underscore to prevent child classes from overriding its value.
MagicObject\Database\PicoDatabaseEntity
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseEntity
Represents a database entity that manages multiple database connections.
Properties
Declaration
Description
An associative array of databases indexed by entity class name.
Declaration
Description
Default database connection
Methods
Declaration
MagicObject $entity,
PicoDatabase|null $database = null
) : self
{
}
Description
Adds an entity to the database.
Parameters
The entity to add.
The database to associate with the entity. If null,
Return
Returns the current instance for method chaining.
Declaration
MagicObject $entity
) : PicoDatabase|null
{
}
Description
Gets the database associated with an entity.
Parameters
The entity whose database is to be retrieved.
Return
Returns the associated database or null if not found.
Declaration
{
}
Description
Get default database connection
Return
Declaration
PicoDatabase $defaultDatabase
) : self
{
}
Description
Set default database connection
Parameters
Default database connection
Return
Returns the current instance for method chaining.
MagicObject\Database\PicoDatabasePersistence
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Database persistence
Constants
Properties
Declaration
Description
Database connection
Declaration
Description
Object
Declaration
Description
Class name
Declaration
Description
Skip null
Declaration
Description
Imported class list
Declaration
Description
Flag that class list has been processed or not
Declaration
Description
Get namespace of class
Declaration
Description
Flag that generated value has been added
Declaration
Description
Flag that entity require database autoincrement
Declaration
Description
Flag that database autoincrement has been completed
Declaration
Description
Table Info
Declaration
Description
Entity table cache
Declaration
Description
Join map
Declaration
Description
Flag that WHERE is defined first
Declaration
Description
WHERE saved on previous
Declaration
Description
Specification
Declaration
Description
Pageable
Declaration
Description
Sortable
Declaration
Description
Join cache
Declaration
Description
The timezone offset for the current session, in the format '+hh:mm' or '-hh:mm'. This offset represents the time difference between the current session's timezone and UTC.
Declaration
Description
The system's timezone offset, representing the offset used by the system's configuration, in the format '+hh:mm' or '-hh:mm'. This offset is typically used when interacting with the system's time settings.
Declaration
Description
The timezone identifier for the current session, e.g., 'Asia/Jakarta'. This timezone is used for time-related operations within the session.
Declaration
Description
The system's timezone identifier, representing the timezone used by the system, e.g., 'Europe/London'. This timezone is typically used for system-level time settings.
Methods
Declaration
PicoDatabase|null $database,
MagicObject|mixed $object
)
{
}
Description
Class constructor to initialize database connection and entity object.
Parameters
Database connection or null
Entity object to be handled
Declaration
string $string
) : bool
{
}
Description
Check if a given string is null or empty.
Parameters
The string to check
Return
True if the string is null or empty, false otherwise
Declaration
string $string
) : bool
{
}
Description
Check if a given string is not null and not empty.
Parameters
The string to check
Return
True if the string is not null and not empty, false otherwise
Declaration
array $data,
array $row,
array $subqueryMap
) : array
{
}
Description
Apply results from a subquery to master data.
Parameters
Master data to which subquery results will be applied
Reference data containing subquery results
Mapping information for subqueries
Return
Updated master data with applied subquery results
Declaration
bool $skip
) : self
{
}
Description
Set a flag to include or skip null columns in the operation.
Parameters
Flag indicating whether to skip null columns
Return
Returns the current instance for method chaining
Declaration
PicoAnnotationParser $reflexClass,
string $queryString,
string $parameter
) : array
{
}
Description
Parse a key-value string using a specified parser.
Parameters
The class used for parsing
The key-value string to parse
The name of the parameter being parsed
Return
Parsed key-value pairs
Throws
If the annotations are invalid or cannot be parsed.
Declaration
array $columns,
PicoAnnotationParser $reflexProp,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add column name to the columns array based on provided parameters.
Parameters
The current columns array
The property parser
The property reflection instance
Parameters containing column name annotations
Return
Updated columns array with new column names
Declaration
array $columns,
PicoAnnotationParser $reflexProp,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add column type information to the columns array.
Parameters
The current columns array
The property parser
The property reflection instance
Parameters containing column type annotations
Return
Updated columns array with new column types
Declaration
array $joinColumns,
PicoAnnotationParser $reflexProp,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add a join column name to the join columns array.
Parameters
The current join columns array
The property parser for the current property
The reflection property instance
Parameters containing join column annotations
Return
Updated join columns array with the new column name
Declaration
array $joinColumns,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add a join column type to the join columns array.
Parameters
The current join columns array
The reflection property instance
Parameters containing join column type annotations
Return
Updated join columns array with the new column type
Declaration
array $primaryKeys,
array $columns,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add primary key information to the primary keys array.
Parameters
The current primary keys array
The columns array
The reflection property instance
Parameters containing primary key annotations
Return
Updated primary keys array with the new primary key
Declaration
array $autoIncrementKeys,
array $columns,
PicoAnnotationParser $reflexClass,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add autogenerated key information to the auto-increment keys array.
Parameters
The current auto-increment keys array
The columns array
The property parser
The reflection property instance
Parameters containing auto-generated value annotations
Return
Updated auto-increment keys array with new autogenerated key
Declaration
array $defaultValue,
array $columns,
PicoAnnotationParser $reflexClass,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add default value information to the default values array.
Parameters
The current default values array
The columns array
The property parser
The reflection property instance
Parameters containing default value annotations
Return
Updated default values array with new default value
Declaration
array $notNullColumns,
array $columns,
ReflectionProperty $prop,
array $parameters
) : array
{
}
Description
Add not-null column information to the not-null columns array.
Parameters
The current not-null columns array
The columns array
The reflection property instance
Parameters containing not-null annotations
Return
Updated not-null columns array with new not-null column
Declaration
{
}
Description
Get table information by parsing class and property annotations.
Return
Table information based on parsed annotations
Throws
If the entity is invalid
Declaration
PDOStatement $stmt,
string|null $databaseType = null
) : bool
{
}
Description
Check if the given PDO statement matches any rows.
Parameters
PDO statement to check.
Optional database type, for specific behavior (e.g., SQLite).
Return
True if rows match, false otherwise.
Declaration
bool $includeNull = false
) : PDOStatement|EntityException
{
}
Description
Save the current object to the database.
Parameters
Whether to include NULL values in the save operation.
Return
Returns the executed statement on success or throws an exception on failure.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}
Description
Construct a query for saving the current object data.
Parameters
Whether to include NULL values in the query.
Return
Returns the constructed query builder for the save operation.
Throws
If an error occurs while constructing the query.
Declaration
PicoTableInfo $info,
PicoDatabaseQueryBuilder $queryBuilder
) : array
{
}
Description
Retrieve the values of the object for database operations.
Parameters
Table information containing column definitions.
Query builder for escaping values.
Return
Associative array of column names and their corresponding values.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Get a list of columns that should be set to NULL.
Parameters
Table information containing column definitions.
Return
List of column names that should be set to NULL.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Retrieve a list of columns that are not insertable.
Parameters
Table information containing column definitions.
Return
List of non-insertable column names.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Retrieve a list of columns that are not updatable.
Parameters
Table information containing column definitions.
Return
List of non-updatable column names.
Declaration
PicoTableInfo $info,
PicoDatabaseQueryBuilder $queryBuilder
) : string
{
}
Description
Construct the SET statement for an SQL update operation.
Parameters
Table information containing column definitions.
Query builder for escaping values.
Return
The constructed SET clause for the update statement.
Throws
If no updatable columns are found.
Declaration
PicoTableInfo $info,
PicoDatabaseQueryBuilder $queryBuilder
) : string
{
}
Description
Construct the WHERE statement for SQL operations.
Parameters
Table information containing primary key definitions.
Query builder for escaping values.
Return
The constructed WHERE clause.
Throws
If no primary keys are defined.
Declaration
PicoTableInfo|null $info = null
) : array
{
}
Description
Retrieve the primary keys from the table information.
Parameters
Optional table information; if null, it retrieves the current table info.
Return
List of primary key column names.
Throws
If an error occurs while retrieving primary keys.
Declaration
PicoTableInfo|null $info = null
) : array
{
}
Description
Retrieve all column names from the table information.
Parameters
Optional table information; if null, it retrieves the current table info.
Return
List of column names.
Throws
If an error occurs while retrieving columns.
Declaration
PicoTableInfo|null $info = null
) : array
{
}
Description
Retrieve all join column names from the table information.
Parameters
Optional table information; if null, it retrieves the current table info.
Return
List of join column names.
Throws
If an error occurs while retrieving join columns.
Declaration
string $columnName,
array $primaryKeys
) : bool
{
}
Description
Check if the specified column name is a primary key.
Parameters
The name of the column to check.
An array of primary key column names.
Return
True if the column is a primary key, false otherwise.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Retrieve primary keys that have auto-increment values.
Parameters
Information about the table, including key definitions.
Return
An associative array of auto-increment primary keys and their values.
Declaration
PicoTableInfo $info,
bool $firstCall
) : self
{
}
Description
Add generated values for auto-increment or UUID fields.
Parameters
Table information.
Indicates whether this is the first call to the method.
Return
Fluent interface; returns the current instance.
Declaration
string $prop,
string $strategy,
bool $firstCall
) : self
{
}
Description
Set a generated value for a specified property based on its generation strategy.
Parameters
The property name to set the generated value for.
The generation strategy to use (e.g., UUID, IDENTITY).
Indicates whether this is the first call to the method.
Return
Fluent interface; returns the current instance.
Declaration
bool $includeNull = false
) : PDOStatement|EntityException
{
}
Description
Insert the current object's data into the database.
Parameters
Whether to include NULL values in the insert operation.
Return
Returns the executed statement on success or throws an exception on failure.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder|EntityException
{
}
Description
Construct the query for inserting the current object's data.
Parameters
Whether to include NULL values in the insert query.
Return
Returns the constructed query builder or throws an exception on failure.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null
) : PDOStatement
{
}
Description
Execute the insert operation using the given table information and query builder.
Parameters
Table information.
Query builder for the insert operation.
Return
The executed statement.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null
) : PicoDatabaseQueryBuilder
{
}
Description
Construct the SQL insert query using the provided table information and query builder.
Parameters
Table information.
Query builder for the insert operation.
Return
The constructed query builder.
Throws
If an error occurs while constructing the query.
Declaration
array $values,
PicoTableInfo|null $info = null
) : array
{
}
Description
Filter the values to only include those that are insertable based on table info.
Parameters
Values to be filtered.
Table information.
Return
The filtered array of insertable values.
Throws
If no values are found that can be inserted.
Declaration
string $strategy,
string $propertyName
) : bool
{
}
Description
Check if a generated value is required based on the strategy and property name.
Parameters
The generation strategy for the property.
The name of the property to check.
Return
True if a generated value is required, false otherwise.
Declaration
array $values
) : string
{
}
Description
Create a comma-separated string of field names for an SQL insert statement.
Parameters
An associative array of values where keys are field names.
Return
A string representation of the field names.
Declaration
array $values
) : string
{
}
Description
Create a comma-separated string of values for an SQL insert statement.
Parameters
An associative array of values.
Return
A string representation of the values.
Declaration
string $propertyNames,
array $columns
) : string
{
}
Description
Convert a property name to its corresponding database column name.
Parameters
A string containing property names.
An array of column definitions.
Return
The resulting string with column names.
Throws
If no column matches the provided property names.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Get a mapping of columns from the provided table information.
Parameters
Table information.
Return
An associative array mapping property names to column names.
Declaration
string $column
) : string
{
}
Description
Adjust the comparison string for SQL queries.
Parameters
The column comparison string.
Return
The adjusted comparison string.
Declaration
PicoTableInfo $info,
string $propertyName,
array $propertyValues
) : string
{
}
Description
Create a SQL WHERE clause based on provided arguments.
Parameters
Table information.
The name of the property to include in the WHERE clause.
The values to compare against.
Return
The constructed WHERE clause.
Declaration
string|null $entityName,
PicoTableInfo $info
) : string|null
{
}
Description
Get table name of the entity
Parameters
Entity name
Table information
Return
The corresponding table name or null if not found
Throws
If unable to retrieve the class name or parse annotations
Declaration
string $entityName,
PicoTableInfo $info
) : string[]
{
}
Description
Get entity primary key of the entity
Parameters
Entity name
Table information
Return
Array of primary key column names
Throws
If unable to retrieve the class name or parse annotations
Declaration
string $entityName,
PicoTableInfo $info
) : array
{
}
Description
Get column maps of the entity
Parameters
Entity name
Table information
Return
Associative array mapping property names to column names
Throws
If unable to retrieve the class name or parse annotations
Declaration
string|null $parentName,
string $masterTable,
string|null $entityTable,
string $field,
bool $master = false
) : string
{
}
Description
Get join source
Parameters
Parent name
Master table
Entity table
Field name
Indicates if the master table is being used
Return
Fully qualified column name for the join
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoSpecification $specification,
PicoTableInfo $info
) : string
{
}
Description
Create WHERE clause from specification
Parameters
Query builder instance
Specification containing filter criteria
Table information
Return
The constructed WHERE clause
Declaration
string[] $arr,
int $max = 0,
string $normalSplit = ' ',
string $maxSplit = ' '
) : string
{
}
Description
Join array of strings with a maximum length for each line
Parameters
Array of strings to join
Maximum length of each line
Normal splitter for joining
Splitter for overflow lines
Return
Joined string with line breaks as necessary
Declaration
string[] $arr,
int $max,
string $normalSplit
) : array
{
}
Description
Split array into chunks based on maximum length
Parameters
Array of strings to split
Maximum length for each chunk
Normal splitter for joining
Return
Array of string chunks
Declaration
array $arr,
array $masterColumnMaps,
PicoDatabaseQueryBuilder $sqlQuery,
PicoSpecification|PicoPredicate|array|string $spec,
PicoTableInfo $info
) : array
{
}
Description
Add WHERE statement to the query
Parameters
Array of existing WHERE clauses
Master column mappings
Query builder instance
Specification to process
Table information
Return
Updated array of WHERE clauses
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoPredicate|string $spec,
string $columnFinal
) : string
{
}
Description
Constructs an SQL query fragment based on the given predicate.
This method generates an SQL condition using a PicoPredicate instance or a raw SQL string.
If the predicate specifies a "BETWEEN" comparison with an array of values, it constructs
a range-based condition. Otherwise, it applies a standard comparison operation.
Parameters
The query builder instance used for SQL operations.
The predicate defining the condition, or a raw SQL string.
The database column to be compared.
Return
The constructed SQL query fragment. Returns an empty string if no valid predicate is provided.
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoPredicate $predicate
) : string
{
}
Description
Construct comparison value for predicates
Parameters
Query builder instance
Predicate with comparison values
Return
Formatted comparison value for SQL query
Declaration
string $column,
string|null $format
) : string
{
}
Description
Format column name with optional formatting
Parameters
Column name to format
Formatting string
Return
Formatted column name
Declaration
PicoTableInfo $info,
PicoSortable|string $order
) : string|null
{
}
Description
Create ORDER BY clause
Parameters
Table information
Sorting criteria
Return
The constructed ORDER BY clause or null
Declaration
PicoSortable $order,
PicoTableInfo|null $info = null
) : string|null
{
}
Description
Create sorting SQL query
Parameters
Sorting criteria
Table information
Return
The constructed ORDER BY clause or null
Declaration
PicoSortable $order,
PicoTableInfo|null $info
) : string|null
{
}
Description
Create sorting without mapping
Parameters
Sorting criteria
Table information
Return
The constructed ORDER BY clause or null
Declaration
PicoSortable $order,
PicoTableInfo $info
) : string
{
}
Description
Create sorting with mapping
Parameters
Sorting criteria
Table information
Return
The constructed ORDER BY clause
Declaration
string[] $primaryKeys,
array $propertyValues
) : bool
{
}
Description
Check if primary keys have valid values
Parameters
Array of primary key names
Property values to check
Return
True if primary keys are valid, false otherwise
Declaration
mixed $propertyValues
) : array
{
}
Description
Convert a scalar value to an array
Parameters
Property values to convert
Return
Converted array of property values
Declaration
PicoTableInfo $info
) : string
{
}
Description
Get all columns of the entity
Parameters
Table information
Return
Comma-separated string of all column names
Declaration
mixed $propertyValues
) : object
{
}
Description
Finds a single record by its primary key value(s).
This method retrieves a single record from the database that matches the specified primary key value(s). It returns the found record as an object. If no record is found or if the filter is invalid, appropriate exceptions will be thrown.
Parameters
The primary key value(s) used to find the record.
Return
The found record, or null if not found.
Throws
If there is an issue with the entity.
If the provided filter criteria are invalid.
If no record is found or no primary key is set.
Declaration
PicoDatabaseQueryBuilder $queryBuilder,
array $primaryKeys,
mixed $propertyValues
) : string
{
}
Description
Creates the WHERE clause for the query based on the primary keys and their values.
This method constructs a WHERE clause for the SQL query using the provided primary key names and values. It checks for null values and properly escapes the values for security.
Parameters
The query builder instance used to create the SQL query.
The primary keys of the table.
The values for the primary keys.
Return
The constructed WHERE clause.
Throws
If the constructed filter is invalid.
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoSpecification|array $specification,
PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}
Description
Add specification to query builder
Parameters
Query builder instance
Specification or specifications array
Table information
Return
Modified query builder with specification applied
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoPageable $pageable
) : PicoDatabaseQueryBuilder
{
}
Description
Add pageable to query builder
Parameters
Query builder instance
Pageable object
Return
Modified query builder with pageable applied
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoPageable|null $pageable,
PicoSortable|string|null $sortable,
PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}
Description
Add sortable to query builder
Parameters
Query builder instance
Pageable object (optional)
Sortable object or field name (optional)
Table information
Return
Modified query builder with sortable applied
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
string $sortOrder
) : PicoDatabaseQueryBuilder
{
}
Description
Set ORDER BY clause in the query
Parameters
Query builder instance
Sort order string
Return
Modified query builder with ORDER BY clause
Declaration
PicoDatabaseQueryBuilder $sqlQuery,
PicoTableInfo $info
) : PicoDatabaseQueryBuilder
{
}
Description
Add JOIN query to the query builder
Parameters
Query builder instance
Table information
Return
Modified query builder with JOIN clauses
Declaration
PicoSpecification $specification,
PicoPageable|null $pageable,
PicoSortable|string|null $sortable,
PicoTableInfo $info
) : bool
{
}
Description
Check if JOIN query is required based on specification, pageable, and sortable
Parameters
Specification object
Pageable object (optional)
Sortable object or field name (optional)
Table information
Return
True if JOIN is required, otherwise false
Declaration
PicoPageable|null $pageable,
PicoSortable|string|null $sortable,
PicoTableInfo $info
) : bool
{
}
Description
Determine if JOIN is required based on pageable and sortable
Parameters
Pageable object (optional)
Sortable object or field name (optional)
Table information
Return
True if JOIN is required, otherwise false
Declaration
PicoSpecification $specification
) : bool
{
}
Description
Determine if JOIN is required based on specification
Parameters
Specification object
Return
True if JOIN is required, otherwise false
Declaration
PicoSpecification $specification,
PicoPageable $pageable,
PicoSortable $sortable,
array|null $subqueryMap = null,
string|null $selected = null
) : PDOStatement
{
}
Description
Create a PDO statement based on specification, pageable, sortable, and selected fields
Parameters
Specification object
Pageable object
Sortable object
Subquery map (optional)
Selected fields (optional)
Return
Prepared PDO statement
Throws
If there is an error in PDO operations
Declaration
PicoSpecification|null $specification,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
PicoTableInfo|null $info = null
) : PicoDatabaseQueryBuilder
{
}
Description
Get query to find all records from the database without any filter
Parameters
Specification object (optional)
Pageable object (optional)
Sortable object or field name (optional)
Table information (optional)
Return
Query builder for finding all records
Declaration
string $selected,
PicoSpecification|null $specification,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
PicoTableInfo|null $info = null
) : PicoDatabaseQueryBuilder
{
}
Description
Get findSpecific query builder
Parameters
The columns to select
Specification to filter results
Pageable information for pagination
Sort order for the results
Table information (optional, defaults to current table info)
Return
The configured query builder
Declaration
PicoSpecification|null $specification,
PicoSortable|string|null $sortable = null,
array|null $subqueryMap = null
) : array|null
{
}
Description
Retrieve a single record from the database without filters
Parameters
Specification to filter results
Sort order for the results
Optional subquery mappings
Return
The retrieved record or null if not found
Throws
If no results are found
Declaration
PicoSpecification|null $specification,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
array|null $subqueryMap = null
) : array|null
{
}
Description
Retrieve all records from the database without filters
Parameters
Specification to filter results
Pageable information for pagination
Sort order for the results
Optional subquery mappings
Return
The list of records or null if not found
Throws
If no results are found
Declaration
mixed $primaryKeyVal,
array $subqueryMap
) : array|null
{
}
Description
Find a record by its primary key value
Parameters
The value of the primary key
Optional subquery mappings
Return
The retrieved record or null if not found
Throws
If no record is found
Declaration
string $selected,
PicoSpecification $specification,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
array|null $subqueryMap = null
) : array|null
{
}
Description
Retrieve records from the database with optional subqueries
Parameters
The columns to select
Specification to filter results
Pageable information for pagination
Sort order for the results
Optional subquery mappings
Return
The list of records or null if not found
Throws
If no results are found
Declaration
PicoTableInfo $info,
array $subqueryMap
) : string
{
}
Description
Create a subquery based on the provided mapping
Parameters
Table information
Mapping for subqueries
Return
The generated subquery string
Declaration
string $string1,
string $string2,
string $separator
) : string
{
}
Description
Concatenate two strings with a separator
Parameters
The first string
The second string
The separator to use
Return
The concatenated string
Declaration
string $selected,
PicoSpecification $specification,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null
) : array|null
{
}
Description
Retrieve specific records from the database
Parameters
The columns to select
Specification to filter results
Pageable information for pagination
Sort order for the results
Return
The list of records or null if not found
Throws
If no results are found
Declaration
string $propertyName,
mixed $propertyValue,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
PicoTableInfo $info = null,
array|null $subqueryMap = null
) : PicoDatabaseQueryBuilder
{
}
Description
Build a query for matched records based on specified criteria
Parameters
The property name to filter by
The value of the property to filter by
Pageable information for pagination
Sort order for the results
Table information
Optional subquery mappings
Return
The configured query builder
Throws
If an error occurs
Declaration
string $propertyName,
mixed $propertyValue,
PicoPageable|null $pageable = null,
PicoSortable|string|null $sortable = null,
array|null $subqueryMap = null
) : array|null
{
}
Description
Retrieve matched records from the database
Parameters
The property name to filter by
The value of the property to filter by
Pageable information for pagination
Sort order for the results
Optional subquery mappings
Return
The list of matched records or null if not found
Throws
If an error occurs
Declaration
string $propertyName,
mixed $propertyValue
) : bool
{
}
Description
Check if a record exists based on property criteria
Parameters
The property name to check
The value of the property to check
Return
True if the record exists, false otherwise
Declaration
PicoSpecification|null $specification = null,
PicoPageable|null $pageable = null,
PicoSortable|null $sortable = null
) : int
{
}
Description
Count the total number of records without filters
Parameters
Specification to filter results
Pageable information for pagination
Sort order for the results
Return
The count of records
Throws
If an error occurs
Declaration
string $propertyName,
mixed $propertyValue
) : int
{
}
Description
Count records based on specified criteria.
Parameters
The property name to filter by.
The value of the property to filter by.
Return
The count of matched records.
Throws
If an error occurs.
Declaration
string $propertyName,
mixed $propertyValue
) : int
{
}
Description
Delete records based on specified criteria without reading them first
Parameters
The property name to filter by
The value of the property to filter by
Return
The number of deleted records
Throws
If an error occurs
Declaration
string $propertyName,
mixed $propertyValue,
PicoSortable|string|null $sortable = null
) : array|null
{
}
Description
Retrieves a single matched record from the database based on the specified property name and value.
This method constructs a SQL query to find a single record that matches the provided property name and value. It can also sort the results based on the optional sortable parameter. If no record is found, it returns null.
Parameters
The name of the property to filter the records by.
The value of the property to match against.
Optional. Defines sorting for the result set.
Return
Returns the matching record as an associative array, or null if no record is found.
Throws
If there is an issue with the entity operations.
If the constructed filter is invalid.
If the query results in an empty set.
Declaration
string $classNameJoin,
PicoTableInfo $info
) : string
{
}
Description
Retrieves the fully qualified class name based on the given class name and table information.
If the class name does not include a namespace, it constructs the full class name using the package information from the provided PicoTableInfo. If the package is not defined, it attempts to resolve the class name from the current namespace or imported classes.
Parameters
The class name to join.
Table information containing package details.
Return
The fully qualified class name, which may include the package or namespace.
Declaration
string $classNameJoin
) : string
{
}
Description
Resolves the fully qualified class name when no package is defined.
This method checks if the class name is present in the imported class list or assumes it belongs to the current namespace if not found. It processes the class list only once to improve efficiency.
Parameters
The class name to join.
Return
The fully qualified class name from the imported list or the same namespace.
Declaration
array $join
) : string
{
}
Description
Retrieves the reference column name from the provided join information.
This method checks if the join array contains a specific key for the reference column name. If the key exists, it returns that value; otherwise, it returns the standard column name.
Parameters
The join column definition, which may include keys for reference and standard column names.
Return
The reference column name, either from the specific key or the standard name.
Declaration
string $classNameJoin,
string $referenceColumName,
PicoTableInfo $info
) : string|null
{
}
Description
Retrieves the property name corresponding to the given reference column name from a joined class.
This method checks the columns of the specified class, and returns the property name that matches the reference column name. If no match is found, it returns the reference column name itself.
Parameters
The name of the class to join with.
The name of the reference column to look up.
The table information containing metadata about the columns.
Return
The corresponding property name if found, otherwise the reference column name.
Declaration
string $classNameJoin
) : self
{
}
Description
Prepares the join cache for a specified class name.
This method checks if the join cache for the given class name exists. If it does not exist, it initializes an empty array for caching join data. It ensures that the join cache is ready for storing results from subsequent queries.
Parameters
The class name for which to prepare the join cache.
Return
Returns the current instance for method chaining.
Declaration
string $classNameJoin,
string $referenceColumnName,
mixed $joinKeyValue,
PicoTableInfo $info
) : MagicObject|null
{
}
Description
Retrieves joined data based on the specified class name and key value.
This method checks the join cache for previously retrieved data. If the data is not found in the cache, it creates a new instance of the specified class, sets the appropriate database connection, and retrieves the data using the specified join key.
Parameters
The name of the class to join with.
The name of the column used as the join key.
The value of the join key to search for.
Table information
Return
Returns the retrieved MagicObject if found, or null if not found.
Declaration
mixed $data,
array $row,
PicoTableInfo $info
) : mixed
{
}
Description
Joins data based on the specified join columns from the provided row.
This method retrieves related data by following the join definitions specified in the
PicoTableInfo object. It populates the given data object with the joined entities
based on the annotations defined in the join columns.
Parameters
The original object or array to be populated with joined data.
The row of data containing column values.
The table information that includes join column metadata.
Return
The updated object or array with joined data.
Declaration
array|object $data,
string $propName,
mixed $value
) : array|object
{
}
Description
Adds a property to the original data array or object.
This method sets a property with the specified name to the given value. It handles both arrays and objects, ensuring that the property is added correctly based on the type.
Parameters
The original data (array or object).
The name of the property to add.
The value to assign to the property.
Return
The updated data array or object with the new property.
Declaration
string $filter
) : bool
{
}
Description
Validates whether the given filter is acceptable.
This method checks if the provided filter is not null, not empty, and not a whitespace string.
Parameters
The filter string to validate.
Return
True if the filter is valid; otherwise, false.
Declaration
string $value
) : bool
{
}
Description
Checks if the provided value is not null, not empty, and not just whitespace.
This method trims the input value and performs checks to determine if it is a valid, non-empty string.
Parameters
The value to check.
Return
True if the value is valid; otherwise, false.
Declaration
array $data,
PicoTableInfo $info
) : array
{
}
Description
Fixes the data types of the input data based on the table information.
This method maps the input data to the appropriate types as defined in the
provided PicoTableInfo. It ensures that the data types are correct according to
the column definitions.
Parameters
The input data to be fixed.
The table information containing type definitions.
Return
The data with fixed types.
Declaration
mixed $value,
string $type
) : mixed
{
}
Description
Fixes the value to the specified data type.
This method converts the input value to the appropriate type based on the provided data type. It handles various types including boolean, integer, double, and DateTime.
Parameters
The input value to be fixed.
The expected data type of the value.
Return
The value converted to the specified type.
Declaration
mixed $value
) : bool
{
}
Description
Converts the input value to a boolean.
This method checks if the input value is equivalent to 1 or '1' to determine
if it should return true; otherwise, it returns false.
Parameters
The input value to convert.
Return
True if the value is equivalent to 1; otherwise, false.
Declaration
mixed $value
) : mixed
{
}
Description
Converts the input value to an integer.
This method returns the integer value of the input. If the input is null, it returns null instead.
Parameters
The input value to convert.
Return
The integer value or null if the input is null.
Declaration
mixed $value
) : mixed
{
}
Description
Converts the input value to a double.
This method returns the double value of the input. If the input is null, it returns null instead.
Parameters
The input value to convert.
Return
The double value or null if the input is null.
Declaration
mixed $value,
array $column
) : mixed
{
}
Description
Fixes the input value based on its type and applies timezone adjustments if necessary.
If the input value is an instance of DateTime, it adjusts the timezone and formats the date according to the specified column format. If the input value is not a DateTime, it simply adjusts the timezone without formatting the value. If a date format is specified in the column, it will format the DateTime accordingly.
Parameters
The input value to fix, which can be a DateTime object, string, or other types.
The column information containing potential date format and type.
Return
The formatted date string if the input is a DateTime, or the original value after timezone adjustment.
Declaration
mixed $value,
array $column,
string|DateTimeZone $timeZoneFrom,
string|DateTimeZone $timeZoneTo
) : mixed
{
}
Description
Adjusts the input value from the source timezone to the target timezone if necessary.
This method checks if the column type is related to a timestamp and the database is SQLite. If so, it adjusts the input value (which can be a DateTime object, string, or Unix timestamp) from the source timezone to the target timezone. Otherwise, it returns the original value.
Parameters
The value to be adjusted. Can be a DateTime, string, or Unix timestamp.
The column information containing potential date format and type.
The source timezone (either a string or DateTimeZone object).
The target timezone (either a string or DateTimeZone object).
Return
The adjusted value, either a formatted DateTime or the original value if no adjustment is necessary.
Declaration
string $value
) : bool
{
}
Description
Checks if the given datetime value represents a null or empty datetime.
This method checks specific string representations of null or default datetime values.
Parameters
The value to check.
Return
True if the value represents a null datetime; otherwise, false.
Declaration
PicoTableInfo $info
) : array
{
}
Description
Creates a mapping of column names to their corresponding property types.
This method generates an associative array where keys are column names and values are their associated property types based on the provided PicoTableInfo.
Parameters
The table information containing column metadata.
Return
An associative array mapping column names to property types.
Declaration
{
}
Description
Selects record from the database based on the defined criteria.
This method builds a query to retrieve records from the database using the current table information, filters, specifications, and pagination settings.
Return
The result set of the query.
Throws
If an error occurs while selecting records.
Declaration
{
}
Description
Selects all records from the database.
This method constructs and executes a query to retrieve all records from the specified table in the database.
Return
The result set containing all records.
Throws
If an error occurs during the selection process.
Declaration
{
}
Description
Builds a query to select data without executing it.
This method prepares a select query using the specified table information and filtering criteria but does not execute the query.
Return
The query builder with the select query prepared.
Throws
If an error occurs while preparing the query.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null,
mixed|null $specification = null,
mixed|null $pageable = null,
mixed|null $sortable = null
) : mixed
{
}
Description
Selects a record from the database based on primary keys.
This method constructs and executes a select query using the provided table information and filtering criteria. It returns the first matching record or null if none found.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Optional specifications for the query.
Optional pagination settings for the query.
Optional sorting settings for the query.
Return
The matching record or null if not found.
Throws
If an error occurs during the selection process.
If the provided filter is invalid.
If no result is found.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null,
mixed|null $specification = null,
mixed|null $pageable = null,
mixed|null $sortable = null
) : array
{
}
Description
Selects all matching records from the database.
This method constructs and executes a select query to retrieve all records that match the specified filtering criteria. It returns an array of results.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Optional specifications for the query.
Optional pagination settings for the query.
Optional sorting settings for the query.
Return
An array of matching records.
Throws
If an error occurs during the selection process.
If the provided filter is invalid.
If no results are found.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null
) : PicoDatabaseQueryBuilder
{
}
Description
Prepares a query to select data without executing it.
This method constructs a select query using the specified table information and filtering criteria without executing it, allowing for further modifications if needed.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Return
The query builder with the select query prepared.
Throws
If the provided filter is invalid.
If an error occurs while preparing the query.
Declaration
bool $includeNull = false
) : PDOStatement
{
}
Description
Updates records in the database.
This method constructs and executes an update query to modify records in the specified table. It accepts an optional flag to include null values in the update.
Parameters
Optional. If true, null values are included in the update.
Return
The executed update statement.
Throws
If an error occurs during the update process.
Declaration
bool $includeNull = false
) : PicoDatabaseQueryBuilder
{
}
Description
Prepares an update query without executing it.
This method constructs an update query using the specified table information and returns the query builder for further modifications.
Parameters
Optional. If true, null values are included in the update.
Return
The query builder with the update query prepared.
Throws
If an error occurs while preparing the query.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null
) : PDOStatement
{
}
Description
Updates a record in the database based on primary keys.
This method constructs and executes an update query using the provided table information and filtering criteria.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Return
The executed update statement.
Throws
If the provided filter is invalid.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null
) : PicoDatabaseQueryBuilder
{
}
Description
Prepares an update query without executing it.
This method constructs an update query using the specified table information and filtering criteria, returning the query builder for further modifications.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Return
The query builder with the update query prepared.
Throws
If the provided filter is invalid.
If an error occurs while preparing the query.
Declaration
{
}
Description
Deletes a record from the database.
This method constructs and executes a delete query to remove a record from the specified table based on the provided filtering criteria.
Return
The executed delete statement.
Throws
If an error occurs during the deletion process.
Declaration
{
}
Description
Prepares a delete query without executing it.
This method constructs a delete query using the specified table information and filtering criteria without executing it, allowing for further modifications.
Return
The query builder with the delete query prepared.
Throws
If an error occurs while preparing the query.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null
) : PDOStatement
{
}
Description
Deletes a record from the database based on primary keys.
This method constructs and executes a delete query using the provided table information and filtering criteria.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Return
The executed delete statement.
Declaration
PicoTableInfo|null $info = null,
PicoDatabaseQueryBuilder|null $queryBuilder = null,
string|null $where = null
) : PicoDatabaseQueryBuilder
{
}
Description
Prepares a delete query without executing it.
This method constructs a delete query using the specified table information and filtering criteria, returning the query builder for further modifications.
Parameters
The table information. If null, fetched internally.
The query builder. If null, created internally.
The where clause for the query. If null, fetched internally.
Return
The query builder with the delete query prepared.
Throws
If the provided filter is invalid.
If an error occurs while preparing the query.
Declaration
PicoSpecification $specification
) : PicoDatabasePersistenceExtended
{
}
Description
Retrieves a MagicObject with a WHERE specification.
This method creates a new instance of PicoDatabasePersistenceExtended and configures it with a WHERE clause derived from the provided specification.
Parameters
The specification used to define the WHERE clause.
Return
The configured persistence object with the WHERE clause.
Declaration
mixed $value
) : bool
{
}
Description
Checks if the given value is an array.
This method verifies whether the provided value is set and is an array.
Parameters
The value to be checked.
Return
True if the value is an array, false otherwise.
Declaration
mixed $input
) : bool
{
}
Description
Check if the given input is not empty.
This function determines if the provided input is set and not empty, returning true if it contains a non-empty value, and false otherwise.
Parameters
The input value to check.
Return
True if the input is not empty, false otherwise.
Declaration
{
}
Description
Get the timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.
Return
Declaration
string $timeZoneOffset
) : self
{
}
Description
Set the timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.
Parameters
The timezone offset for the current session, represented in the format '+hh:mm' or '-hh:mm'.
Return
Declaration
{
}
Description
Get the system's timezone offset in the format '+hh:mm' or '-hh:mm'.
This method returns the system's timezone offset, which is stored as a string in the format of hours and minutes (e.g., '+07:00', '-03:00').
Return
The system's timezone offset.
Declaration
string $timeZoneOffsetSystem
) : self
{
}
Description
Set the system's timezone offset in the format '+hh:mm' or '-hh:mm'.
This method sets the system's timezone offset, which should be provided as a string in the format of hours and minutes (e.g., '+07:00', '-03:00').
Parameters
The timezone offset to set for the system.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the timezone used for time-related operations within the session.
This method returns the timezone identifier (e.g., 'Asia/Jakarta') that is set for the current session and is used for all time-related operations.
Return
The timezone identifier for the current session (e.g., 'Asia/Jakarta').
Declaration
string $timeZone
) : self
{
}
Description
Set the timezone used for time-related operations within the session.
This method sets the timezone identifier (e.g., 'Asia/Jakarta') to be used for all time-related operations in the current session.
Parameters
The timezone identifier to be used for time-related operations (e.g., 'Asia/Jakarta').
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the timezone typically used for system-level time settings.
This method returns the system's timezone identifier (e.g., 'Europe/London') which is generally used for system-level time settings and configurations.
Return
The system's timezone identifier (e.g., 'Europe/London').
Declaration
string $timeZoneSystem
) : self
{
}
Description
Set the timezone typically used for system-level time settings.
This method sets the system's timezone identifier (e.g., 'Europe/London') that is typically used for system configurations and time settings.
Parameters
The timezone identifier to be used for system-level time settings (e.g., 'Europe/London').
Return
Returns the current instance for method chaining.
MagicObject\Database\PicoDatabasePersistenceExtended
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Database persistence extended
This class extends the functionality of the PicoDatabasePersistence by adding dynamic property setting through magic methods and enhanced record selection capabilities.
Properties
Declaration
Description
@var array An array of property-value pairs where each entry contains the name of a property and its corresponding value.
Declaration
Description
Database connection
Declaration
Description
Object
Declaration
Description
Class name
Declaration
Description
Join map
Declaration
Description
Flag that WHERE is defined first
Declaration
Description
WHERE saved on previous
Declaration
Description
Specification
Declaration
Description
Pageable
Declaration
Description
Sortable
Methods
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Sets a property value and adds it to the internal map.
This method sets a value to a property of the associated object and adds the property name and value to an internal map for further processing.
Parameters
The name of the property to set.
The value to assign to the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Adds the property name and value to the internal map.
This method adds the given property name and value as an entry in the internal $map array.
Parameters
The name of the property.
The value of the property.
Return
Returns the current instance for method chaining.
Declaration
string $method,
mixed[] $params
) : $this
{
}
Description
Magic method to handle undefined methods for setting properties.
This method dynamically handles method calls that start with "set". It allows setting properties of the object in a more flexible way, using a consistent naming convention.
Supported dynamic method:
set<PropertyName>: Sets the value of the specified property.- If the property name follows "set", the method extracts the property name and assigns the provided value to it.
- If no value is provided, it sets the property to null.
- Example:
$obj->setFoo($value)sets the propertyfooto$value.
Parameters
The name of the method that was called.
The parameters passed to the method, expected to be an array.
Return
Returns the current instance for method chaining.
Declaration
MagicObject $entity
) : PicoDatabase
{
}
Description
Get the current database for the specified entity.
This method retrieves the database connection associated with the provided entity. If the entity does not have an associated database or if the connection is not valid, it defaults to the object's primary database connection.
Parameters
The entity for which to get the database.
Return
The database connection for the entity.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only. It converts the object to a JSON string that represents the current state of the object, including the 'where' specification and the 'set' mapping, making it easier to inspect the internal data during development.
Return
The JSON string representation of the object, containing:
MagicObject\Database\PicoDatabaseQueryBuilder
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseQueryBuilder
A query builder for constructing SQL statements programmatically. This class facilitates the creation of various SQL commands including SELECT, INSERT, UPDATE, and DELETE, while managing database-specific nuances.
Example:
<?php
$id = 100;
$db = new PicoDatabase($credentials);
$db->connect();
$query = new PicoDatabaseQueryBuilder($db);
$query
->select("*")
->from("client")
->where("client_id = ?", $id)
;
$data = $db->fetch($query);
echo $data['client_id']."\r\n"; // Client ID
echo $data['name']."\r\n"; // Client name
Properties
Declaration
Description
Buffer to hold the constructed SQL query.
Declaration
Description
Indicates whether limit and offset have been set.
Declaration
Description
The limit for the number of results.
Declaration
Description
The offset for the results.
Declaration
Description
The type of database being used.
Declaration
Description
Flag indicating if values have been set.
Methods
Declaration
PicoDatabase|PDO|string $database
)
{
}
Description
Initializes a new instance of the PicoDatabaseQueryBuilder class.
This constructor accepts various types of database connections:
- If a
PicoDatabaseinstance is provided, the database type is retrieved from it. - If a
PDOinstance is provided, the driver name is used to determine the database type. - If a string is provided, it is assumed to be the database type.
Parameters
The database connection or type.
Declaration
{
}
Description
Get the value of the database type.
Return
The database type.
Declaration
{
}
Description
Check if the database type is MySQL or MariaDB.
Return
True if the database type is MySQL or MariaDB, false otherwise.
Declaration
{
}
Description
Check if the database type is PostgreSQL.
Return
True if the database type is PostgreSQL, false otherwise.
Declaration
{
}
Description
Check if the database type is SQLite.
Return
True if the database type is SQLite, false otherwise.
Declaration
{
}
Description
Check if the database type is SQL Server.
Return
True if the database type is SQLite, false otherwise.
Declaration
{
}
Description
Initialize a new SQL query by resetting the buffer, limit, and offset.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Create an insert statement.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Specify the table to insert into.
Parameters
The name of the table.
Return
Returns the current instance for method chaining.
Declaration
mixed $query
) : self
{
}
Description
Specify the fields to insert values into.
Parameters
The field names (string or array).
Return
Returns the current instance for method chaining.
Declaration
mixed $query
) : self
{
}
Description
Specify the values to be inserted.
Parameters
The values to insert (string, array, or multiple parameters).
Return
Returns the current instance for method chaining.
Declaration
string $query = ''
) : self
{
}
Description
Create a select statement.
Parameters
The fields to select (optional).
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create an alias for a field or table.
Parameters
The alias to use.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Create a delete statement.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Specify the source table for the query.
Parameters
The name of the table.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create an inner join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create an outer join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a left outer join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a left join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a right join statement.
Parameters
The join details.
Return
Returns the current instance for method chaining.
Declaration
mixed $query
) : self
{
}
Description
Create an ON statement for JOIN operations.
Parameters
The join condition(s).
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create an UPDATE statement for a specified table.
Parameters
The name of the table to update.
Return
Returns the current instance for method chaining.
Declaration
mixed $query
) : self
{
}
Description
Specify the fields and values to set in the UPDATE statement.
Parameters
The field(s) and value(s) to set.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a WHERE statement for filtering results.
Parameters
The condition(s) for the WHERE clause.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Binds SQL parameters by replacing placeholders with actual values.
This function accepts multiple arguments, where the first argument
is expected to be a SQL string containing ? placeholders, and
subsequent arguments are the values to replace them.
Return
The formatted SQL query with values replaced.
Declaration
array $args
) : string
{
}
Description
Create a matched value string from the given arguments.
Parameters
The arguments to match.
Return
The formatted string.
Declaration
string $table,
array $data
) : string
{
}
Description
Create an INSERT query for a specified table.
Parameters
The name of the table.
The data to be inserted.
Return
The constructed INSERT query.
Declaration
string $table,
array $data,
array $primaryKey
) : string
{
}
Description
Create an UPDATE query for a specified table.
Parameters
The name of the table.
The data to be updated.
The primary keys for the update condition.
Return
The constructed UPDATE query.
Declaration
string $query
) : self
{
}
Description
Create a HAVING statement for filtering aggregated results.
Parameters
The condition(s) for the HAVING clause.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create an ORDER BY statement for sorting results.
Parameters
The field(s) to order by.
Return
Returns the current instance for method chaining.
Declaration
string $query
) : self
{
}
Description
Create a GROUP BY statement for grouping results.
Parameters
The field(s) to group by.
Return
Returns the current instance for method chaining.
Declaration
int $limit
) : self
{
}
Description
Set a limit on the number of results returned.
Parameters
The maximum number of results.
Return
Returns the current instance for method chaining.
Declaration
int $offset
) : self
{
}
Description
Set an offset for the results returned.
Parameters
The offset from the start of the result set.
Return
Returns the current instance for method chaining.
Declaration
string $tables
) : string|null
{
}
Description
Create a LOCK TABLES statement for database locking.
Parameters
Comma-separated table names to lock.
Return
The LOCK TABLES statement or null if not supported.
Declaration
{
}
Description
Create an UNLOCK TABLES statement to release table locks.
Return
The UNLOCK TABLES statement or null if not supported.
Declaration
{
}
Description
Create a START TRANSACTION statement for initiating a transaction.
Return
The START TRANSACTION statement or null if not supported.
Declaration
{
}
Description
Create a COMMIT statement to finalize a transaction.
Return
The COMMIT statement or null if not supported.
Declaration
{
}
Description
Create a ROLLBACK statement to revert a transaction.
Return
The ROLLBACK statement or null if not supported.
Declaration
string $query
) : string
{
}
Description
Escape special characters in a SQL string.
This method escapes special characters in a SQL query string to prevent SQL injection and ensure proper execution across different database systems. It handles various database types (SQLite, MySQL/MariaDB, PostgreSQL, and SQL Server) by applying database-specific escaping techniques:
- For MySQL/MariaDB, it uses
addslashesfor special characters and escapes newline characters. - For PostgreSQL and SQLite, it uses a custom quote replacement function and escapes newline characters.
- For SQL Server, it doubles the single quote characters (
') to escape them.
Parameters
The SQL query string to escape. This should be a valid
Return
The escaped SQL query string. This result can be safely used
Declaration
mixed $value
) : string
{
}
Description
Escape a value for SQL queries.
This method safely escapes different types of values (null, strings, booleans, numeric values, arrays, and objects) to ensure that they can be safely used in SQL queries. It prevents SQL injection by escaping potentially dangerous characters in string values and converts arrays or objects to their JSON representation.
Parameters
The value to be escaped. Can be null, string, boolean,
Return
The escaped value. This will be a string representation
Declaration
mixed $values
) : string
{
}
Description
Escapes the JSON-encoded values.
This function takes an input value, encodes it into JSON format, and then escapes the resulting JSON string to ensure it is safe for use (e.g., preventing injection or special character issues).
Parameters
The input values to be encoded into JSON and escaped.
Return
The escaped JSON string.
Declaration
mixed $value
) : string
{
}
Description
Convert a value to its boolean representation for SQL.
For SQLite, returns '1' for true and '0' for false. For other databases, returns 'TRUE' for true and 'FALSE' for false.
Parameters
The value to be converted.
Return
The boolean representation as a string.
Declaration
array $values
) : string
{
}
Description
Convert an array to a comma-separated list of escaped values.
Parameters
The array of values.
Return
The comma-separated list.
Declaration
string $name,
string $params
) : string|null
{
}
Description
Create a statement to execute a function.
Parameters
The name of the function to execute.
The parameters for the function.
Return
The SQL statement to execute the function or null if not supported.
Declaration
string $name,
string $params
) : string|null
{
}
Description
Create a statement to execute a stored procedure.
Parameters
The name of the procedure to execute.
The parameters for the procedure.
Return
The SQL statement to execute the procedure or null if not supported.
Declaration
{
}
Description
Create a statement to retrieve the last inserted ID.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Create a statement to get the current date.
Return
The SQL statement for the current date or null if not supported.
Declaration
{
}
Description
Create a statement to get the current time.
Return
The SQL statement for the current time or null if not supported.
Declaration
{
}
Description
Create a statement to get the current timestamp.
Return
The SQL statement for the current timestamp or null if not supported.
Declaration
int $precision = 0
) : string
{
}
Description
Create a NOW statement for the current time with optional precision.
Parameters
The decimal precision of seconds (default is 0).
Return
The NOW statement with the specified precision.
Declaration
string $query
) : string
{
}
Description
Replace single quotes with double single quotes in a SQL string for escaping.
Parameters
The SQL query string to modify.
Return
The modified SQL query string.
Declaration
string $query
) : string
{
}
Description
Add query parameters to a SQL statement.
Parameters
The SQL query string.
Return
The constructed SQL query with parameters.
Declaration
string $queryString,
PicoPageable|null $pageable,
PicoSortable|null $sortable
) : string
{
}
Description
Adds pagination and sorting clauses to a native query string.
This function appends the appropriate ORDER BY and LIMIT $limit OFFSET $offset or LIMIT $offset, $limit
clauses to the provided SQL query string based on the given pagination and sorting parameters.
It supports various database management systems (DBMS) and adjusts the query syntax
accordingly (e.g., for PostgreSQL, SQLite, MySQL, MariaDB, etc.).
Parameters
The original SQL query string to which pagination and sorting will be added.
The pagination parameters, or null if pagination is not required.
The sorting parameters, or null if sorting is not required.
Return
The modified SQL query string with added pagination and sorting clauses.
Declaration
{
}
Description
Converts the current object to a string representation.
This method casts the current object to a string. It relies on the magic method __toString() to provide a meaningful string representation of the object.
Return
The string representation of the object.
Declaration
{
}
Description
Magic method that converts the object to a string representation.
This method generates a SQL query string based on the object's buffer and the limit/offset properties. The exact SQL syntax depends on the database type being used (MySQL, PostgreSQL, SQLite, or SQL Server).
Return
The generated SQL query string with pagination (if applicable).
MagicObject\Database\PicoDatabaseQueryTemplate
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseQueryTemplate
This class represents a query template or builder that can either hold a pre-defined query template (as a string) or an instance of a query builder (PicoDatabaseQueryBuilder). It is designed to facilitate the construction and conversion of queries to a string format, either directly or through a query builder.
Properties
Declaration
Description
The query template as a string.
This property holds the template for a database query in string format, or null if no template is provided.
Declaration
Description
The query builder instance.
This property holds an instance of PicoDatabaseQueryBuilder, which is used to build and manipulate database queries programmatically.
Methods
Declaration
PicoDatabaseQueryBuilder|string|null $query
)
{
}
Description
PicoDatabaseQueryTemplate constructor.
The constructor accepts either a query builder object or a query template string. It initializes the appropriate property based on the type of the provided argument.
Parameters
The query builder object or query template string.
Declaration
{
}
Description
Converts the object to a string representation.
This method returns the string representation of the query. If a query builder instance is set, it will return the string representation of the builder. If a query template string is provided, it will return that template string. If neither is set, it will return an empty string.
Return
The string representation of the query, either from the builder or template.
MagicObject\Database\PicoDatabaseStructure
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Represents the structure of a database table.
This class is used to manage and generate the structure of a database table based on annotations
defined in a MagicObject class. It provides functionality to create SQL CREATE TABLE statements
and retrieve metadata about the table, including its columns, primary keys, and nullable fields.
It uses annotations such as @Table to specify the table name and @Column to define column properties
in a class. The class can automatically generate SQL statements for creating a table and its columns
based on this metadata.
The class also provides utility methods for retrieving table information, such as column definitions,
and for handling column attributes like nullable, primary, and notnull.
Constants
Properties
Declaration
Description
The associated MagicObject instance.
Declaration
Description
The name of the class representing the table.
Methods
Declaration
MagicObject $object
)
{
}
Description
Constructor to initialize the PicoDatabaseStructure with a MagicObject.
Parameters
The MagicObject representing the database structure.
Declaration
string $databaseType,
string|null $tableName = null
) : string
{
}
Description
Generates a CREATE TABLE statement based on the object's metadata.
Parameters
The type of database (e.g., MySQL, MariaDB).
Optional name of the table. If not provided, it will be inferred.
Return
The SQL CREATE TABLE statement.
Throws
If no table name is provided and cannot be inferred.
Declaration
string $databaseType,
PicoTableInfo $info
) : string
{
}
Description
Generates the CREATE TABLE syntax based on the database type and table information.
Parameters
The type of database (e.g., MySQL).
The table information containing column definitions.
Return
The SQL column definitions for the CREATE TABLE statement.
Declaration
mixed $nullable
) : string
{
}
Description
Returns the NULL/NOT NULL declaration based on the nullable setting.
Parameters
Indicates if the column is nullable.
Return
The corresponding NULL or NOT NULL declaration.
Declaration
PicoAnnotationParser $reflexClass,
string $queryString,
string $parameter
) : array
{
}
Description
Parses a key-value string from an annotation.
Parameters
The reflection of the class containing the annotation.
The string to be parsed.
The parameter name for error reporting.
Return
The parsed key-value pairs.
Throws
If the annotations are invalid or cannot be parsed.
Declaration
{
}
Description
Retrieves metadata about the object, including table name and column definitions.
Return
An instance containing the table name and column information.
Declaration
{
}
Description
Get the associated MagicObject instance.
MagicObject\Database\PicoDatabaseType
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseType
Defines constants for various database types supported by the MagicObject framework. This class provides a centralized reference to these types, enhancing code clarity and maintainability.
Supported database types include:
- MySQL
- MariaDB
- PostgreSQL
- SQLite
- SQL Server
Constants
MagicObject\Database\PicoDataComparation
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDataComparation
This class provides various comparison operations for use in database queries. It allows the creation of comparison objects that can be utilized to compare values against specified criteria, facilitating flexible and expressive database querying.
The class supports a variety of comparison operators such as equality, inequality, inclusion, and range comparisons. Each operator can be applied to values of various types, including strings, booleans, and numbers.
Constants
Properties
Declaration
Description
The comparison operator.
Declaration
Description
The value to compare against.
Declaration
Description
The type of the value.
Methods
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for equality.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for inequality.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed[] $values
) : self
{
}
Description
Creates a comparison for inclusion in a set.
Parameters
The values to compare against.
Return
Returns the current instance for method chaining.
Declaration
mixed[] $values
) : self
{
}
Description
Creates a comparison for inclusion within a range.
Parameters
The range boundaries to compare against.
Return
Returns the current instance for method chaining.
Declaration
mixed $min,
mixed $max
) : self
{
}
Description
Creates a comparison for values within a specified range.
Parameters
The lower boundary of the range.
The upper boundary of the range.
Return
Returns the current instance for method chaining.
Declaration
mixed[] $values
) : self
{
}
Description
Creates a comparison for exclusion from a set.
Parameters
The values to compare against.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison using the LIKE operator.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison using the NOT LIKE operator.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for less than.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for greater than.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for less than or equal to.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value
) : self
{
}
Description
Creates a comparison for greater than or equal to.
Parameters
The value to compare.
Return
Returns the current instance for method chaining.
Declaration
mixed $value,
string $comparison = '='
)
{
}
Description
Constructor for PicoDataComparation.
Parameters
The value to compare.
The comparison operator.
Declaration
{
}
Description
Returns the appropriate equals operator based on the value's state.
If the value is null or of type null, returns the IS operator; otherwise, returns the standard equals operator.
Return
The equals operator.
Declaration
{
}
Description
Returns the appropriate not equals operator based on the value's state.
If the value is null or of type null, returns the IS NOT operator; otherwise, returns the standard not equals operator.
Return
The not equals operator.
Declaration
{
}
Description
Returns the less than operator.
Return
The less than operator.
Declaration
{
}
Description
Returns the greater than operator.
Return
The greater than operator.
Declaration
{
}
Description
Returns the less than or equals operator.
Return
The less than or equals operator.
Declaration
{
}
Description
Returns the greater than or equals operator.
Return
The greater than or equals operator.
Declaration
{
}
Description
Determines the comparison operator based on the current value and its type.
Return
The comparison operator corresponding to the current state.
Declaration
{
}
Description
Gets the value being compared.
Return
The value that is currently being compared.
MagicObject\Database\PicoEntityField
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing an entity field in a database.
This class encapsulates information about an entity field, including its associated entity, field name, and any parent field relationships.
Properties
Declaration
Description
The associated entity.
Declaration
Description
The object name associated with the field.
Declaration
Description
The field name.
Declaration
Description
The parent field name.
Declaration
Description
The function format for the field.
Methods
Declaration
string $fieldRaw,
PicoTableInfo|null $info = null
)
{
}
Description
Constructor for PicoEntityField.
Parameters
The raw field input.
Table information (optional).
Declaration
{
}
Description
Get the associated entity.
Return
The entity name.
Declaration
{
}
Description
Get the field name.
Return
The field name.
Declaration
{
}
Description
Get the parent field name.
Return
The parent field name.
Declaration
{
}
Description
Get the function format for the field.
Return
The function format.
Declaration
string $fieldRaw
) : string
{
}
Description
Extract the field name from a raw field input.
If the input contains a function, it extracts the field name and updates the function format.
Parameters
The raw field input.
Return
The extracted field name.
MagicObject\Database\PicoEntityLabel
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class to manage entity labels and their annotations.
Provides methods to retrieve and filter entity metadata, including labels, columns, and other attributes.
Constants
Properties
Declaration
Description
The class name of the entity.
Declaration
Description
Supported languages for labels.
Methods
Declaration
MagicObject $object,
string[] $langs
)
{
}
Description
Constructor for the PicoEntityLabel class.
Parameters
The entity object.
Supported languages.
Declaration
string|null $lang = null
) : array|null
{
}
Description
Get the mapping of labels based on the specified language.
Parameters
The language to filter the labels by.
Return
The filtered labels, or null if the language is not supported.
Declaration
array $merged,
string|null $lang
) : array|null
{
}
Description
Filter the merged labels based on the specified language.
Parameters
Merged array of labels.
The language to filter by.
Return
The filtered labels, or null if the language is not supported.
Declaration
PicoAnnotationParser $reflexClass,
string $queryString,
string $parameter
) : array
{
}
Description
Parse a key-value string from the annotation parser.
Parameters
Reflection class for the entity.
The query string to parse.
The parameter name.
Return
The parsed key-value pairs.
Throws
If the annotations are invalid or cannot be parsed.
Declaration
{
}
Description
Get object information, including metadata about labels, columns, and more.
Return
An object containing entity metadata.
MagicObject\Database\PicoJoinMap
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing a join mapping in a database.
Contains information about how an entity is joined with another table.
Properties
Declaration
Description
The property name in the entity.
Declaration
Description
The column name in the join table.
Declaration
Description
The name of the entity being joined.
Declaration
Description
The name of the join table.
Declaration
Description
The alias for the join table.
Methods
Declaration
string $propertyName,
string $columnName,
string $entity,
string $joinTable,
string $joinTableAlias
)
{
}
Description
Constructor for PicoJoinMap.
Parameters
The property name.
The column name.
The entity name.
The join table name.
The join table alias.
Declaration
{
}
Description
Get the property name.
Return
The property name.
Declaration
{
}
Description
Get the column name.
Return
The column name.
Declaration
{
}
Description
Get the entity name.
Return
The entity name.
Declaration
{
}
Description
Get the join table name.
Return
The join table name.
Declaration
{
}
Description
Get the join table alias.
Return
The join table alias.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoLimit
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoLimit
This class provides functionality to manage pagination in database queries by setting limits and offsets for record retrieval.
Properties
Declaration
Description
The maximum number of records to retrieve.
Declaration
Description
The number of records to skip before starting to collect the result set.
Methods
Declaration
int $offset = 0,
int $limit = 0
)
{
}
Description
Constructor to initialize offset and limit.
Parameters
The number of records to skip. Default is 0.
The maximum number of records to retrieve. Default is 0.
Declaration
{
}
Description
Increment the offset to retrieve the next page of records.
This method adjusts the offset based on the current limit, allowing for the retrieval of the next set of records in a paginated result.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Decrement the offset to retrieve the previous page of records.
This method adjusts the offset back, ensuring it does not fall below zero, thus allowing navigation to the previous set of records.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the maximum number of records to retrieve.
Return
Declaration
int $limit
) : self
{
}
Description
Set the maximum number of records to retrieve.
This method ensures that the limit is at least 1.
Parameters
The maximum number of records.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the current offset for record retrieval.
Return
Declaration
int $offset
) : self
{
}
Description
Set the number of records to skip before starting to collect the result set.
This method ensures that the offset is not negative.
Parameters
The number of records to skip.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get information about the current page based on the offset and limit.
This method calculates the current page number and returns a PicoPage object containing the page number and limit.
Return
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoPage
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing a data page for pagination.
This class provides functionality to manage page numbers and sizes, and to calculate offsets for database queries.
Properties
Declaration
Description
Page number.
Declaration
Description
Page size (number of items per page).
Methods
Declaration
int $pageNumber = 1,
int $pageSize = 1
)
{
}
Description
Constructor.
Initializes the page number and page size.
Parameters
Page number (default is 1).
Page size (default is 1).
Declaration
{
}
Description
Increase the page number by one.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Decrease the page number by one, ensuring it doesn't go below 1.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Retrieves the current page number.
Return
The current page number.
Declaration
int $pageNumber
) : self
{
}
Description
Set the page number.
Parameters
Page number.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Retrieves the page size (number of items per page).
Return
The page size.
Declaration
int $pageSize
) : self
{
}
Description
Set the page size.
Parameters
Page size.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Calculates and retrieves the offset for database queries.
The offset is used to determine the starting point for fetching data in paginated queries, based on the current page number and page size.
Return
The calculated offset for database queries.
Declaration
{
}
Description
Calculates the limit and offset for database queries.
Return
An instance of PicoLimit with the calculated offset and limit.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoPageable
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Pageable
Properties
Declaration
Description
Current page information.
Declaration
Description
Sortable information.
Declaration
Description
Offset and limit for database queries.
Methods
Declaration
PicoPage|PicoLimit|array|null $page = null,
PicoSortable|array|null $sortable = null
)
{
}
Description
Constructor for the Pageable class.
This constructor allows initializing a Pageable object with pagination and sorting options. It supports different formats for both page and sortable parameters.
Example 1: Using PicoPage and PicoSortable
<?php
$pageable = new Pageable(new PicoPage(1, 100), new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
?>
Example 2: Using PicoLimit and PicoSortable
<?php
$pageable = new Pageable(new PicoLimit(0, 100), new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
?>
Example 3: Using an array for page and PicoSortable
<?php
$pageable = new Pageable([1, 100], new PicoSortable('userName', 'asc', 'email', 'desc', 'phone', 'asc'));
?>
Example 4: Using an array for both page and sortable
<?php
$pageable = new Pageable([1, 100], ['userName', 'asc', 'email', 'desc', 'phone', 'asc']);
?>
Example 5: Using PicoPage and an array for sortable
<?php
$pageable = new Pageable(new PicoPage(1, 100), ['userName', 'asc', 'email', 'desc', 'phone', 'asc']);
?>
Parameters
The page or limit configuration. Can be:
The sorting configuration. Can be:
Declaration
{
}
Description
Retrieves the sortable information.
Return
Declaration
PicoSortable $sortable
) : self
{
}
Description
Sets the sortable information.
Parameters
Sortable information.
Return
Returns the current instance for method chaining.
Declaration
string $sortBy,
string $sortType
) : self
{
}
Description
Adds a sortable criterion.
Parameters
The field to sort by.
The type of sorting (e.g., 'asc' or 'desc').
Return
Returns the current instance for method chaining.
Throws
If $sortBy is null or empty.
Declaration
PicoTableInfo $tableInfo
) : string|null
{
}
Description
Creates the ORDER BY clause based on the current sortable criteria.
Parameters
Information about the table.
Return
The ORDER BY clause or null if no sortable criteria exist.
Declaration
{
}
Description
Retrieves the current page information.
Return
Declaration
PicoPage $page
) : self
{
}
Description
Sets the current page information.
Parameters
Page information.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Retrieves the offset and limit for database queries.
Return
Declaration
PicoLimit $offsetLimit
) : self
{
}
Description
Sets the offset and limit for database queries.
Parameters
Offset and limit information.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoPageControl
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoPageControl
This class manages pagination controls for displaying pages of data. It generates navigation elements such as previous, next, first, and last page buttons, allowing users to navigate through pages seamlessly. The pagination links are generated based on the provided page data and can be customized with parameter names and paths.
Properties
Declaration
Description
Page data object containing pagination information.
Declaration
Description
Parameter name used for pagination in the URL.
Declaration
Description
Base path for pagination links.
Declaration
Description
Symbol for the previous page button.
Declaration
Description
Symbol for the next page button.
Declaration
Description
Symbol for the first page button.
Declaration
Description
Symbol for the last page button.
Declaration
Description
Template for rendering a specific page number in pagination.
Declaration
Description
Template for rendering navigation buttons like "next" or "prev" in pagination.
Declaration
Description
Template for rendering navigation buttons like "first" or "last" in pagination.
Methods
Declaration
PicoPageData $pageData,
string $parameterName = 'page',
string|null $path = null
)
{
}
Description
Constructor for the PicoPageControl class.
Initializes pagination control with page data and optional parameter name and path.
Parameters
Page data object for pagination.
Parameter name for the page (default is 'page').
Full path for generating pagination links (optional).
Declaration
mixed $value
) : bool
{
}
Description
Checks if a value is set and not empty.
Parameters
The value to check.
Return
Returns true if the value is set and not empty, otherwise false.
Declaration
string|null $prev = null,
string|null $next = null,
string|null $first = null,
string|null $last = null
) : self
{
}
Description
Sets custom navigation symbols for pagination buttons.
This method allows you to define custom symbols for navigation buttons, including the previous, next, first, and last page buttons. Only non-null values will be assigned to their respective properties.
Parameters
The symbol to display for the "previous" page button (optional).
The symbol to display for the "next" page button (optional).
The symbol to display for the "first" page button (optional).
The symbol to display for the "last" page button (optional).
Return
Returns the current instance for method chaining.
Declaration
int $margin
) : self
{
}
Description
Sets the margin for pagination controls.
This defines how many pages to show before and after the current page.
Parameters
Margin (number of pages before and after the current page).
Return
Returns the current instance for method chaining.
Declaration
int $range
) : self
{
}
Description
Sets the range for pagination controls.
This defines how many pages to show before and after the current page.
Parameters
Range (number of pages before and after the current page).
Return
Returns the current instance for method chaining.
Declaration
int $range
) : self
{
}
Description
Sets the page range for pagination controls.
This defines how many pages to show before and after the current page.
Parameters
Range (number of pages before and after the current page).
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the template for rendering specific page numbers.
Return
The current format for rendering page numbers.
Declaration
string $formatPageNumber
) : self
{
}
Description
Sets the template for rendering specific page numbers.
This format is used to generate the HTML for individual page numbers in the pagination.
It includes a span with the page-selector-number class and a link (<a>) to the page.
Placeholders:
%s: Additional CSS classes, e.g.,page-selected.%d: Page number for thedata-page-numberattribute.%s: URL for the link (hrefattribute).-
%s: Text content of the link (usually the page number).Example:
<span class="page-selector page-selector-number%s" data-page-number="%d"><a href="%s">%s</a></span>will be
<span class="page-selector page-selector-number page-selected" data-page-number="3"> <a href="/path?page=3">3</a> </span>
Parameters
The new format for rendering page numbers.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the template for rendering step navigation buttons.
Return
The current format for step navigation buttons.
Declaration
string $formatStepOne
) : self
{
}
Description
Sets the template for rendering step navigation buttons.
This format generates the HTML for step navigation buttons, such as "previous" or "next."
It includes a span with the page-selector-step-one class and a link (<a>) to the target page.
Placeholders:
%s: Additional CSS classes (e.g., active state).%d: Page number for thedata-page-numberattribute.%s: URL for the link (hrefattribute).-
%s: Symbol or text for the button (e.g., "Next" or "Prev").Example:
<span class="page-selector page-selector-step-one%s" data-page-number="%d"><a href="%s">%s</a></span>will be
<span class="page-selector page-selector-step-one" data-page-number="4"> <a href="/path?page=4">Next</a> </span>
Parameters
The new format for step navigation buttons.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the template for rendering end navigation buttons.
Return
The current format for end navigation buttons.
Declaration
string $formatStartEnd
) : self
{
}
Description
Sets the template for rendering end navigation buttons.
This format generates the HTML for step navigation buttons, such as "previous" or "next."
It includes a span with the page-selector-step-one class and a link (<a>) to the target page.
Placeholders:
%s: Additional CSS classes (e.g., active state).%d: Page number for thedata-page-numberattribute.%s: URL for the link (hrefattribute).-
%s: Symbol or text for the button (e.g., "Start" or "End").Example:
<span class="page-selector page-selector-end%s" data-page-number="%d"><a href="%s">%s</a></span>will be
<span class="page-selector page-selector-end" data-page-number="4"> <a href="/path?page=4">End</a> </span>
Parameters
The new format for end navigation buttons.
Return
Returns the current instance for method chaining.
Declaration
string $pageNumberFormat,
string $stepOneFormat,
string $startEndFormat
) : self
{
}
Description
Sets the button format templates for pagination controls.
This method allows you to set custom templates for page numbers, step buttons and start/end buttons.
Parameters
The format template for rendering page numbers.
The format template for rendering step buttons.
The format template for rendering start and end buttons.
Return
Returns the current instance for method chaining.
Declaration
SecretObject $paginationConfig
) : self
{
}
Description
Applies the pagination configuration to the current instance.
This method accepts a configuration object, typically sourced from a Yaml file, and applies its settings to the pagination control. The object contains the following properties:
Parameters
The configuration object containing pagination settings.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Converts the pagination control to HTML format.
Return
HTML representation of the pagination controls.
Declaration
{
}
Description
Generates the HTML for pagination controls.
Return
HTML representation of the pagination controls.
MagicObject\Database\PicoPageData
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing paginated data for database queries.
The PicoPageData class encapsulates the results of a database query along with pagination details,
execution timing, and other metadata. It provides methods to manage and retrieve paginated results
effectively, allowing for easy integration into applications that require data manipulation and display.
Key Features
- Encapsulates query results in a paginated format.
- Supports execution time tracking for performance monitoring.
- Provides easy access to pagination controls and metadata.
- Facilitates fetching and processing of data with subquery mapping.
Constants
Properties
Declaration
Description
Result data from the query.
Declaration
Description
Pageable object that defines pagination settings.
Declaration
Description
Total number of matching results from the query.
Declaration
Description
Total number of pages based on pagination settings.
Declaration
Description
Current page number in the pagination context.
Declaration
Description
Number of results per page.
Declaration
Description
Offset for retrieving data in the current pagination context.
Declaration
Description
Start time of the query execution.
Declaration
Description
End time of the query execution.
Declaration
Description
Total execution time for the query in seconds.
Declaration
Description
Array holding pagination details for display.
Declaration
Description
PDO statement associated with the query execution.
Declaration
Description
Class name of the entity being managed.
Declaration
Description
Mapping information for subqueries.
Declaration
Description
Flag indicating whether the result was derived from a count query.
Declaration
Description
Entity associated with the results.
Declaration
Description
Flags for controlling find options in the query.
Methods
Declaration
MagicObject[]|null $result = null,
float $startTime = null,
int $totalResult = 0,
PicoPageable|null $pageable = null,
PDOStatement|null $stmt = null,
MagicObject|null $entity = null,
array|null $subqueryMap = null
)
{
}
Description
Constructor for the PicoPageData class.
Initializes a new instance of the class with the specified parameters.
Parameters
Array of MagicObject instances or null.
Timestamp when the query was initiated.
Total count of results, defaults to 0.
Pageable object for pagination settings.
PDO statement associated with the query.
Entity associated with the query results.
Mapping for subquery results.
Declaration
array $result
) : int
{
}
Description
Count the number of items in the result set.
Parameters
Result set to count.
Return
Count of items in the result.
Declaration
{
}
Description
Calculate pagination content based on the pageable settings.
Return
Returns the current instance for method chaining.
Declaration
int $countResult
)
{
}
Description
Initialize default pagination settings.
This method is called when no pageable object is provided.
Parameters
Total count of results.
Declaration
int $pageRange = 3
) : self
{
}
Description
Generate pagination details for display.
This method constructs an array of pagination controls based on the current page number and total pages.
Parameters
Number of pages to show before and after the current page.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get result data from the query.
Return
Array of MagicObject instances.
Declaration
{
}
Description
Get the current page number in the pagination context.
Return
Current page number.
Declaration
{
}
Description
Get the total number of pages based on pagination settings.
Return
Total page count.
Declaration
{
}
Description
Get the size of each page (number of results per page).
Return
Page size.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
Declaration
{
}
Description
Get the execution time of the query in seconds.
Return
Execution time.
Declaration
{
}
Description
Get the pagination details for the current query.
Return
Pagination details.
Declaration
string $parameterName = 'page',
string|null $path = null
) : PicoPageControl
{
}
Description
Get the pagination control object for managing page navigation.
Parameters
Parameter name for the page.
Optional link path.
Return
Pagination control object.
Declaration
{
}
Description
Get the total result count from the query.
Return
Total result count.
Declaration
{
}
Description
Get the pageable object associated with this data.
Return
Pageable object or null if not set.
Declaration
{
}
Description
Get the data offset for the current pagination context.
Return
Data offset.
Declaration
{
}
Description
Get the PDO statement associated with the query.
Return
Throws
if the statement is null.
Declaration
{
}
Description
Fetch the next row from the result set.
Return
Next row data as a MagicObject or false on failure.
Throws
if the statement is null.
Declaration
array $row
) : MagicObject
{
}
Description
Apply subquery results to the row data.
This method processes the row data and integrates results from subqueries as defined by the mapping.
Parameters
Data row from the query result.
Return
Processed MagicObject instance containing the merged data.
Declaration
{
}
Description
Get find option flags indicating query behavior.
Return
Find option flags.
Declaration
int $findOption
) : self
{
}
Description
Set find option flags to control query behavior.
Parameters
Flags indicating the desired query options.
Return
Returns the current instance for method chaining.
MagicObject\Database\PicoPredicate
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoPredicate
A predicate for building query conditions in database queries. This class allows you to define various query conditions (e.g., equality, inequality, inclusion, pattern matching, etc.) to be used when constructing database queries.
Properties
Methods
Declaration
string|null $field = null,
mixed|null $value = null
)
{
}
Description
Constructor. Initializes the predicate with a field and value.
If a field is provided, it sets the equality condition or an IN condition based on the value type.
Parameters
The name of the field.
The value to compare against.
Declaration
{
}
Description
Check if a real join table is required.
Return
True if a join is required, false otherwise.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set an equality condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a not-equal condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field
) : self
{
}
Description
Set a condition for NULL.
Parameters
The name of the field.
Return
Returns the current instance for method chaining.
Declaration
string $field
) : self
{
}
Description
Set a condition for NOT NULL.
Parameters
The name of the field.
Return
Returns the current instance for method chaining.
Declaration
string $field,
array $values
) : self
{
}
Description
Set an IN condition.
Parameters
The name of the field.
The values to include.
Return
Returns the current instance for method chaining.
Declaration
string $field,
array $values
) : self
{
}
Description
Sets an IN RANGE condition.
Parameters
The name of the field to compare.
An array containing the lower and upper boundaries of the range.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $min,
mixed $max
) : self
{
}
Description
Sets a BETWEEN condition.
Parameters
The name of the field to compare.
The lower boundary of the range.
The upper boundary of the range.
Return
Returns the current instance for method chaining.
Declaration
string $field,
array $values
) : self
{
}
Description
Set a NOT IN condition.
Parameters
The name of the field.
The values to exclude.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a LIKE condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a NOT LIKE condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a LESS THAN condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a GREATER THAN condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a LESS THAN OR EQUALS condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
string $field,
mixed $value
) : self
{
}
Description
Set a GREATER THAN OR EQUALS condition.
Parameters
The name of the field.
The value to compare against.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the field name.
Return
The name of the field.
Declaration
{
}
Description
Get the value.
Return
The value being compared against.
Declaration
{
}
Description
Get the comparation instance.
Return
The comparation instance or null.
Declaration
{
}
Description
Get the filter logic.
Return
The filter logic or null.
Declaration
string $filterLogic
) : self
{
}
Description
Set the filter logic.
Parameters
The filter logic to set.
Return
Returns the current instance for method chaining.
Declaration
string $value
) : string
{
}
Description
Generate a LIKE clause that matches the start of a string.
Parameters
The value to use for matching.
Return
The LIKE clause for matching the start.
Declaration
string $value
) : string
{
}
Description
Generate a LIKE clause that matches the end of a string.
Parameters
The value to use for matching.
Return
The LIKE clause for matching the end.
Declaration
string $value
) : string
{
}
Description
Generate a LIKE clause that matches anywhere in a string.
Parameters
The value to use for matching.
Return
The LIKE clause for matching anywhere.
Declaration
string $method,
array $params
) : mixed
{
}
Description
Magic method to handle dynamic method calls for setting values.
This method intercepts calls to methods that are not explicitly defined in the class. It specifically looks for methods that start with "set" and performs an equality check between the property corresponding to the method and the provided value.
Supported dynamic method:
-
set<PropertyName>(value): Checks if the property value equals the provided value.- For example, calling
$obj->setFoo($value)checks if the propertyfoois equal to$valueusing theequalsmethod.
If the method name does not start with "set" or if no value is provided, the method returns null.
- For example, calling
Parameters
The method name being called, expected to start with "set".
The parameters passed to the method, expected to contain the value.
Return
The result of the equality check (true or false) or null if the method call is not handled.
Declaration
string $name,
mixed $value
)
{
}
Description
Magic method to handle dynamic property assignment.
This method allows for setting property values dynamically.
Parameters
The property name.
The value to set.
Declaration
{
}
Description
Get an instance of this class.
Return
A new instance of PicoPredicate.
Declaration
string $value
) : string
{
}
Description
Generate a SQL LOWER function call.
Parameters
The value to wrap in the LOWER function.
Return
The SQL LOWER function call.
Declaration
string $value
) : string
{
}
Description
Generate a SQL UPPER function call.
Parameters
The value to wrap in the UPPER function.
Return
The SQL UPPER function call.
Declaration
string $function,
string $value
) : string
{
}
Description
Generate a SQL function call with a value.
Parameters
The SQL function name.
The value to pass to the function.
Return
The formatted SQL function call.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoSort
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoSort
A class for defining sorting criteria for database queries. This class allows you to specify the field to sort by and the direction of sorting (ascending or descending).
Constants
Properties
Declaration
Description
The field to sort by.
Declaration
Description
The type of sorting (ascending or descending).
Methods
Declaration
string|null $sortBy = null,
string|null $sortType = null
)
{
}
Description
Constructor to initialize sorting criteria.
Parameters
The field to sort by.
The type of sorting (asc or desc).
Declaration
{
}
Description
Get the field to sort by.
Return
The field to sort by.
Declaration
string $sortBy
) : self
{
}
Description
Set the field to sort by.
Parameters
The field to sort by.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the type of sorting.
Return
The type of sorting (asc or desc).
Declaration
string $sortType
) : self
{
}
Description
Set the type of sorting.
Parameters
The type of sorting (asc or desc).
Return
Returns the current instance for method chaining.
Declaration
string $method,
array $params
) : self|null
{
}
Description
Magic method for dynamic method calls related to sorting criteria.
This method enables the dynamic setting of sorting criteria by allowing the invocation of methods prefixed with "sortBy". When such a method is called, it extracts the sorting field from the method name and assigns a sorting type based on the provided parameters.
Supported dynamic method:
-
sortBy<FieldName>(sortType): Sets the field to sort by and the type of sorting.- For example, calling
$obj->sortByName('asc')would:- Set the sorting field to
name. - Set the sorting type to
asc.
- Set the sorting field to
If the method name does not start with "sortBy" or if no parameters are provided, the method returns null.
- For example, calling
Parameters
The name of the method being called, expected to start with "sortBy".
The parameters passed to the method; expected to contain the sorting type.
Return
Returns the current instance for method chaining or null if the method call is not handled.
Declaration
{
}
Description
Get an instance of PicoSort.
Return
A new instance of PicoSort.
Declaration
string $type
) : string
{
}
Description
Normalize the sort type to either ascending or descending.
Parameters
The desired sort type (asc or desc).
Return
The normalized sort type (asc or desc).
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
MagicObject\Database\PicoSortable
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing sortable criteria for database queries.
This class provides functionality to manage sorting criteria, allowing the specification of fields to sort by and their sort types.
Properties
Declaration
Description
Array of sortable criteria.
Methods
Declaration
{
}
Description
Constructor to initialize sortable criteria based on provided arguments.
Example:
<?php
$sortable = new PicoSortable(); // Without initialization
// or
$sortable = new PicoSortable("rank", "ASC", "name", "ASC"); // With initialization
Declaration
int $argc,
array $params
) : self
{
}
Description
Initialize sortable criteria.
Parameters
Number of arguments passed to the constructor.
Parameters for sorting.
Return
Returns the current instance for method chaining.
Declaration
PicoSort|array|string $sort,
bool $isRawSql = false
) : self
{
}
Description
Add a sortable criterion.
Parameters
The sorting criterion to add.
Indicates whether the array-based sorting is raw SQL.
Return
Returns the current instance for method chaining.
Declaration
PicoSort|array|string $sort,
bool $isRawSql = false
) : self
{
}
Description
Add a sortable criterion.
Parameters
The sorting criterion to add.
Indicates whether the array-based sorting is raw SQL.
Return
Returns the current instance for method chaining.
Declaration
string $sortBy,
string $sortType
) : PicoSort
{
}
Description
Create a sortable criterion.
Parameters
The field to sort by.
The type of sorting (ASC or DESC).
Return
Declaration
PicoTableInfo|null $tableInfo = null
) : string|null
{
}
Description
Create an ORDER BY clause based on the sortable criteria.
Parameters
Information about the table for mapping.
Return
The ORDER BY clause, or null if there are no sortable criteria.
Declaration
{
}
Description
Create an ORDER BY clause without mapping to table columns.
Return
The ORDER BY clause.
Declaration
PicoTableInfo $tableInfo
) : string
{
}
Description
Create an ORDER BY clause with mapping based on table information.
Parameters
Information about the table for mapping.
Return
The ORDER BY clause.
Declaration
{
}
Description
Check if there are no sortable criteria.
Return
True if there are no sortable criteria, false otherwise.
Declaration
{
}
Description
Get the array of sortable criteria.
Return
Array of sortable criteria.
Declaration
{
}
Description
Get an instance of PicoSortable.
Return
A new instance of PicoSortable.
Declaration
{
}
Description
Generates the ORDER BY clause without mapping.
This method is useful for debugging purposes.
Return
The generated ORDER BY clause.
Declaration
PicoRequestBase $request,
string[]|null $map = null,
array|null $defaultSortable = null
) : self
{
}
Description
Create a PicoSortable instance from user input.
Parameters
The request containing sorting information.
Mapping of request parameters to sorting fields.
Default sorting criteria if no user input is provided.
Return
A new instance of PicoSortable with the specified criteria.
Declaration
mixed $array
) : bool
{
}
Description
Check if the given input is an array.
Parameters
The input to check.
Return
True if the input is an array, false otherwise.
MagicObject\Database\PicoSpecification
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoSpecification
This class is responsible for building complex database query specifications, allowing for the combination of predicates using logical operators (AND, OR).
Constants
Properties
Declaration
Description
Parent filter logic (AND/OR) for nested specifications.
Declaration
Description
Array of PicoPredicate objects representing individual conditions.
Declaration
Description
Indicates whether a real join table is required in the database query.
Declaration
Description
Default logic for combining predicates (AND/OR).
Methods
Declaration
{
}
Description
Gets an instance of PicoSpecification.
Return
A new instance of PicoSpecification.
Declaration
string|null $field = null,
mixed|null $value = null
) : self
{
}
Description
Creates and returns an instance of the class with an optional PicoPredicate condition.
This static method creates a new instance of the class and, if the provided parameters are set, adds a PicoPredicate condition using the given field and value.
Parameters
The name of the field to be used in the predicate.
The value to compare against the field in the predicate.
Return
A new instance of the class with the optionally added predicate.
Declaration
{
}
Description
Checks if a real join table is required based on the specifications.
Return
True if a join is required, false otherwise.
Declaration
PicoSpecification|PicoPredicate|array|string $predicate
) : self
{
}
Description
Adds a specification with default AND logic.
This method allows adding a filtering condition using logical AND.
The condition can be a PicoPredicate, PicoSpecification, an array representing a predicate, or a raw SQL condition as a string.
Parameters
The filter condition to be added.
Return
Returns the current instance for method chaining.
Declaration
PicoSpecification|PicoPredicate|array|string $predicate
) : self
{
}
Description
Adds an AND condition to the specifications.
This method allows adding a filtering condition using logical AND.
The condition can be a PicoPredicate, PicoSpecification, an array representing a predicate, or a raw SQL condition as a string.
Parameters
The filter condition to be added.
Return
Returns the current instance for method chaining.
Declaration
PicoSpecification|PicoPredicate|array|string $predicate
) : self
{
}
Description
Adds an OR condition to the specifications.
Similar to addAnd(), but applies logical OR instead of AND.
Parameters
The filter condition to be added.
Return
Returns the current instance for method chaining.
Declaration
PicoSpecification|PicoPredicate|array|string $predicate,
string $logic
) : self
{
}
Description
Adds a filtering condition to the specifications.
This method processes the given predicate and applies the specified logical operator (AND/OR).
If the predicate is an instance of PicoPredicate, it will be modified to include the logical operator.
If a PicoSpecification is provided, its specifications will be extracted and added recursively.
If the predicate is an array, it will be processed accordingly.
If a raw SQL string is provided, it will be added with the logical operator.
Parameters
The filter condition to be added.
The logical operator (AND or OR) to be applied.
Return
Returns the current instance for method chaining.
Declaration
array $predicate,
string $logic
) : self
{
}
Description
Adds a filter specification from an array.
Parameters
The filter data represented as an associative array.
The logical operator (AND/OR) to use with these filters.
Return
Returns the current instance for method chaining.
Declaration
PicoSpecification|array $predicate,
string $logic
) : self
{
}
Description
Adds a subfilter specification.
Parameters
The subfilter to be added.
The logical operator (AND/OR) to use with this subfilter.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Checks if the specifications collection is empty.
Return
True if there are no specifications, false otherwise.
Declaration
mixed $array
) : bool
{
}
Description
Check if the given input is an array.
Parameters
The input to check.
Return
True if the input is an array, false otherwise.
Declaration
mixed $value
) : bool
{
}
Description
Checks if the given value is considered empty.
Parameters
The value to check.
Return
True if the value is empty, false otherwise.
Declaration
{
}
Description
Retrieves the array of specifications.
Return
The array of PicoPredicate objects.
Declaration
{
}
Description
Gets the parent filter logic for this specification.
Return
The parent filter logic, or null if not set.
Declaration
string $parentFilterLogic
) : self
{
}
Description
Sets the parent filter logic for this specification.
Parameters
The logical operator (AND/OR) for this specification.
Return
Returns the current instance for method chaining.
Declaration
PicoSpecification[] $specifications
) : string[]
{
}
Description
Creates a WHERE clause based on the current specifications.
Parameters
The specifications to create the WHERE clause from.
Return
An array of strings representing the WHERE clause conditions.
Declaration
string $field,
string|null $parentField
) : string
{
}
Description
Retrieves the full column name, including any parent field.
This method returns the column name formatted as "parentField.field" if the parent field is provided; otherwise, it returns just the field name.
Parameters
The field name of the entity.
The parent field name, if applicable.
Return
The full column name, either just the field name or the parent field concatenated with the field.
Declaration
PicoSpecification $specification
) : string
{
}
Description
Creates a WHERE clause from the given specification.
Parameters
The filter specification to create the WHERE clause from.
Return
The constructed WHERE clause as a string.
Declaration
mixed $specification
) : bool
{
}
Description
Checks if the specification is not null and not empty.
Parameters
The specification to check.
Return
True if the specification is valid, false otherwise.
Declaration
string $method,
array $params
) : self|null
{
}
Description
Magic method to handle undefined method calls dynamically.
This method allows for dynamic handling of method calls that are not explicitly defined in the class.
Specifically, it enables the setting of properties through methods prefixed with "set".
When such a method is called, the method extracts the property name from the method name,
and then it calls the addPredicate method to set the corresponding value.
Supported dynamic method:
-
set<FieldName>(value): Sets a predicate for the specified field. For example, calling$obj->setAge(30)would:- Extract the field name
agefrom the method name. - Call
addPredicate('age', 30)to set the value.
If the method name does not start with "set" or if the parameters are not provided, the method returns null.
- Extract the field name
Parameters
The name of the method being called, expected to start with "set".
The parameters passed to the method; expected to contain the value to set.
Return
Returns the current instance for method chaining if the method is valid, or null otherwise.
Declaration
string $field,
mixed|mixed[] $value
)
{
}
Description
Magic method to set values dynamically using property assignment.
Parameters
The field name to set.
The value(s) to set for the field.
Declaration
string $field,
mixed|mixed[] $value
) : self
{
}
Description
Adds a predicate to the specifications based on the field and value.
Parameters
The field name to which the value is assigned.
The value(s) to set for the field.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Creates a part of the WHERE clause from specifications for debugging purposes only.
Removes leading logical operators (AND, OR) if present.
Return
The generated WHERE clause.
Declaration
PicoRequestBase $request,
PicoSpecificationFilter[]|null $map = null
) : PicoSpecification
{
}
Description
Gets a specification based on user input.
Parameters
The request object containing user input.
The filter map defining expected filters.
Return
The constructed specification based on user input.
Declaration
array $input
) : array
{
}
Description
Converts all string values in an array to lowercase.
Parameters
The input array containing string values.
Return
The modified array with all values converted to lowercase.
Declaration
mixed $filterValue,
PicoSpecificationFilter $filter
) : mixed
{
}
Description
Adjusts the filter value based on the filter's configuration.
This method ensures that the input value aligns with the filter type. If the filter does not expect an array but the input is an array, the first value in the array is selected. If no adjustment is needed, the input value is returned as-is.
Parameters
The raw user input value.
The filter object specifying expected data type.
Return
The adjusted value, based on the filter's configuration.
Declaration
string $columnName,
string $keywords
) : self
{
}
Description
Creates a full text search specification based on keywords.
Parameters
The column name to search within.
The keywords to search for.
Return
A new specification containing the full text search predicates.
Declaration
string $columnName,
array $keywordArray
) : self
{
}
Description
Creates a full-text search specification for an array of keyword sets. Each set of keywords is processed separately, allowing for multiple search conditions. Uses an OR condition between different keyword sets and an AND condition within each set.
Parameters
The database column name to search within.
An array of keyword sets, where each element contains a string of keywords.
Return
A new specification containing the combined full-text search predicates.
Declaration
string $columnName,
string $dataType
) : PicoSpecificationFilter
{
}
Description
Creates a filter object based on column name and data type.
Parameters
The column name to filter by.
The data type of the column (e.g., string, integer).
Return
A new instance of PicoSpecificationFilter.
Declaration
{
}
Description
Gets the default logic used for combining predicates.
Return
The default logic (AND/OR).
Declaration
string $defaultLogic
) : self
{
}
Description
Sets the default logic used for combining predicates.
Parameters
The default logic (AND/OR) to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Sets the default logic to AND.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Sets the default logic to OR.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Checks if a real join table is required based on the specifications.
Return
True if a join is required, false otherwise.
MagicObject\Database\PicoSpecificationFilter
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing a specification filter.
This class defines filters for columns, specifying the data type and providing methods to convert values based on the defined type.
Constants
Properties
Declaration
Description
The name of the column this filter applies to.
Declaration
Description
The data type of the column (e.g., number, string, boolean).
Methods
Declaration
string $columnName,
string $dataType
)
{
}
Description
Constructor for PicoSpecificationFilter.
Initializes the column name and data type.
Parameters
The name of the column.
The data type of the column.
Declaration
{
}
Description
Convert the object to a JSON string representation for debugging.
This method is intended for debugging purposes only and provides a JSON representation of the object's state.
Return
The JSON representation of the object.
Declaration
mixed $stringValue
) : mixed
{
}
Description
Converts a given value to the appropriate type based on the filter's data type.
Parameters
The value to convert.
Return
The converted value, typecasted as needed.
Declaration
{
}
Description
Checks if the data type represents an array.
This method determines whether the data type contains
an array-like structure based on the presence of square brackets ([]).
Return
True if the data type represents an array, false otherwise.
Declaration
mixed $stringValue
) : float[]|int[]
{
}
Description
Converts a value to an array of numbers.
Parameters
The value to convert.
Return
An array of numeric values.
Declaration
mixed $stringValue
) : bool[]
{
}
Description
Converts a value to an array of booleans.
Parameters
The value to convert.
Return
An array of boolean values.
Declaration
mixed $stringValue
) : float|int
{
}
Description
Converts a value to a number.
Parameters
The value to convert.
Return
The converted numeric value.
Declaration
mixed $stringValue
) : bool
{
}
Description
Converts a value to a boolean.
Parameters
The value to convert.
Return
The converted boolean value.
Declaration
{
}
Description
Checks if the data type is a number.
Return
True if the data type is a number, false otherwise.
Declaration
{
}
Description
Checks if the data type is a string.
Return
True if the data type is a string, false otherwise.
Declaration
{
}
Description
Checks if the data type is a boolean.
Return
True if the data type is a boolean, false otherwise.
Declaration
{
}
Description
Checks if the data type is an array of numbers.
Return
True if the data type is an array of numbers, false otherwise.
Declaration
{
}
Description
Checks if the data type is an array of strings.
Return
True if the data type is an array of strings, false otherwise.
Declaration
{
}
Description
Checks if the data type is an array of booleans.
Return
True if the data type is an array of booleans, false otherwise.
Declaration
{
}
Description
Checks if the data type is full text.
Return
True if the data type is full text, false otherwise.
Declaration
{
}
Description
Gets the column name of this filter.
Return
The name of the column.
Declaration
{
}
Description
Gets the data type of this filter.
Return
The data type of the column.
MagicObject\Database\PicoSqlite
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class PicoSqlite
A simple wrapper for SQLite database operations using PDO.
This class provides an easy-to-use interface for interacting with an SQLite database. It supports basic CRUD (Create, Read, Update, Delete) operations such as creating tables, inserting records, selecting records with optional conditions, updating records, and deleting records.
The class uses PDO (PHP Data Objects) for database connectivity and supports executing SQL queries through various methods. The connection to the SQLite database is made through the provided file path, and additional callbacks can be provided for query execution and debugging.
This class extends the PicoDatabase class, which provides additional database interaction capabilities.
Constants
Properties
Declaration
Description
Database file path
Declaration
Description
Database credential.
Declaration
Description
Indicates whether the database is connected or not.
Declaration
Description
Autocommit setting.
Declaration
Description
Database connection.
Declaration
Description
Database type.
Declaration
Description
Callback function when executing queries that modify data.
Declaration
Description
Callback function when executing any query.
Methods
Declaration
string $tableName
) : bool
{
}
Description
Check if a table exists in the database.
Parameters
The name of the table to check.
Return
True if the table exists, false otherwise.
Declaration
string $tableName,
string[] $columns
) : int|false
{
}
Description
Create a new table in the database.
Parameters
The name of the table to create.
An array of columns in the format 'column_name TYPE'.
Return
Returns the number of rows affected or false on failure.
Declaration
string $tableName,
array $data
) : bool
{
}
Description
Insert a new record into the specified table.
Parameters
The name of the table to insert into.
An associative array of column names and values to insert.
Return
Returns true on success or false on failure.
Declaration
string $tableName,
array $conditions = array ( )
) : array
{
}
Description
Select records from the specified table with optional conditions.
Parameters
The name of the table to select from.
An associative array of conditions for the WHERE clause.
Return
Returns an array of fetched records as associative arrays.
Declaration
string $tableName,
array $data,
array $conditions
) : bool
{
}
Description
Update existing records in the specified table based on conditions.
Parameters
The name of the table to update.
An associative array of column names and new values.
An associative array of conditions for the WHERE clause.
Return
Returns true on success or false on failure.
Declaration
string $tableName,
array $conditions
) : bool
{
}
Description
Delete records from the specified table based on conditions.
Parameters
The name of the table to delete from.
An associative array of conditions for the WHERE clause.
Return
Returns true on success or false on failure.
MagicObject\Database\PicoSqlJson
Declaration
Package
MagicObject\DatabaseDescription
Class PicoSqlJson
This class handles the encoding and validation of JSON data. It accepts an object, array, or a valid JSON string and ensures that it is properly encoded as a JSON string. If a string is provided, it checks if the string is a valid JSON format before encoding it. If the string is not valid JSON, an exception will be thrown.
Properties
Declaration
Description
The JSON encoded value
Methods
Declaration
mixed $value = null
)
{
}
Description
Constructor for PicoSqlJson class
Accepts an array, object, or a valid JSON string, and encodes it to JSON. If a string is provided, it checks whether it's a valid JSON string. If valid, it is encoded to JSON; otherwise, an exception is thrown.
Parameters
The value to encode. Can be an array, object, or JSON string.
Throws
If the string provided is not valid JSON.
Declaration
{
}
Description
Converts the object to a string.
This method returns the JSON-encoded value of the object when the object is treated as a string (e.g., when echoing or concatenating the object).
Return
The JSON string representation of the object.
MagicObject\Database\PicoTableInfo
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing information about a database table.
This class contains details such as the table name, columns, primary keys, and other related metadata necessary for managing database interactions.
Properties
Declaration
Description
The name of the table.
Declaration
Description
The columns of the table.
Declaration
Description
The columns used for joining other tables.
Declaration
Description
The primary keys of the table.
Declaration
Description
The columns that auto-increment.
Declaration
Description
The columns that have default values.
Declaration
Description
The columns that cannot be null.
Declaration
Description
The type of the columns.
Declaration
Description
Flag to disable cache when any entities join with this entity
Declaration
Description
The package name or namespace.
Declaration
Description
List of sorted column names.
This property stores an array of column names in their sorted order.
Methods
Declaration
{
}
Description
Gets an instance of PicoTableInfo.
Return
A new instance of PicoPredicate.
Declaration
string|null $tableName,
array $columns,
array $joinColumns,
array $primaryKeys,
array $autoIncrementKeys,
array $defaultValue,
array $notNullColumns,
bool $noCache = false,
string $package = null
)
{
}
Description
Constructor for PicoTableInfo.
Initializes the table information with the provided parameters.
Parameters
The name of the table.
The columns of the table.
The columns used for joins.
The primary keys of the table.
The auto-increment keys of the table.
The columns with default values.
The columns that cannot be null.
Flag to disable cache when any entities join with this entity
The package name or namespace of the class
Declaration
{
}
Description
Magic method to return a JSON representation of the object.
Return
JSON encoded string of the object's properties.
Declaration
{
}
Description
Gets a map of column properties.
Return
An associative array mapping property names to column names.
Declaration
{
}
Description
Gets a map of join column properties.
Return
An associative array mapping property names to join column names.
Declaration
{
}
Description
Gets the name of the table.
Return
The name of the table.
Declaration
string $tableName
) : self
{
}
Description
Sets the name of the table.
Parameters
The name of the table.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the columns of the table.
Return
The columns of the table.
Declaration
array $columns
) : self
{
}
Description
Sets the columns of the table.
Parameters
The columns to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the join columns of the table.
Return
The join columns.
Declaration
array $joinColumns
) : self
{
}
Description
Sets the join columns of the table.
Parameters
The join columns to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the primary keys of the table.
Return
The primary keys.
Declaration
array $primaryKeys
) : self
{
}
Description
Sets the primary keys of the table.
Parameters
The primary keys to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the auto-increment keys of the table.
Return
The auto-increment keys.
Declaration
array $autoIncrementKeys
) : self
{
}
Description
Sets the auto-increment keys of the table.
Parameters
The auto-increment keys to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the default value keys of the table.
Return
The default value keys.
Declaration
array $defaultValue
) : self
{
}
Description
Sets the default value keys of the table.
Parameters
The default value keys to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Gets the not-null columns of the table.
Return
The not-null columns.
Declaration
array $notNullColumns
) : self
{
}
Description
Sets the not-null columns of the table.
Parameters
The not-null columns to set.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get flag to disable cache when any entities join with this entity
Return
Declaration
boolean $noCache
) : self
{
}
Description
Set flag to disable cache when any entities join with this entity
Parameters
Flag to disable cache when any entities join with this entity
Return
Declaration
{
}
Description
Get the package name or namespace.
Return
Declaration
string $package
) : self
{
}
Description
Set the package name or namespace.
Parameters
The package name or namespace.
Return
Declaration
{
}
Description
Get the sorted column names.
This method retrieves the list of sorted column names.
Return
List of sorted column names.
Declaration
array $sortedColumnName
) : self
{
}
Description
Set the sorted column names.
This method sets the list of sorted column names.
Parameters
List of sorted column names.
Return
Returns the current instance for method chaining.
MagicObject\Database\PicoTableInfoExtended
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class representing extended information about a database table.
This class extends the functionality of PicoTableInfo by providing methods for managing unique columns, join columns, primary keys, auto-increment keys, default values, and not-null columns.
Constants
Properties
Declaration
Description
The name of the table.
Declaration
Description
The columns of the table.
Declaration
Description
The columns used for joining other tables.
Declaration
Description
The primary keys of the table.
Declaration
Description
The columns that auto-increment.
Declaration
Description
The columns that have default values.
Declaration
Description
The columns that cannot be null.
Declaration
Description
The type of the columns.
Declaration
Description
Flag to disable cache when any entities join with this entity
Declaration
Description
The package name or namespace.
Methods
Declaration
{
}
Description
Removes duplicate columns based on their names.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Removes duplicate join columns based on their names.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Removes duplicate primary keys based on their names.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Removes duplicate auto-increment keys based on their names.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Removes duplicate default value keys based on their names.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Removes duplicate not-null columns based on their names.
Return
Returns the current instance for method chaining.
Declaration
array $tmp,
array $oldListCheck,
array $newList
) : array
{
}
Description
Merges a new list of items into an existing temporary list.
Parameters
The temporary list.
The old list to check against.
The new list to merge.
Return
The updated temporary list.
Declaration
array $oldList
) : array
{
}
Description
Retrieves the old list for checking against.
Parameters
The old list to retrieve.
Return
An array of column names from the old list.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of columns into the existing columns, ensuring uniqueness.
Parameters
The new list of columns to merge.
Return
Returns the current instance for method chaining.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of join columns into the existing join columns, ensuring uniqueness.
Parameters
The new list of join columns to merge.
Return
Returns the current instance for method chaining.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of primary keys into the existing primary keys, ensuring uniqueness.
Parameters
The new list of primary keys to merge.
Return
Returns the current instance for method chaining.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of auto-increment keys into the existing auto-increment keys, ensuring uniqueness.
Parameters
The new list of auto-increment keys to merge.
Return
Returns the current instance for method chaining.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of default value keys into the existing default value keys, ensuring uniqueness.
Parameters
The new list of default value keys to merge.
Return
Returns the current instance for method chaining.
Declaration
array $newList
) : self
{
}
Description
Merges a new list of not-null columns into the existing not-null columns, ensuring uniqueness.
Parameters
The new list of not-null columns to merge.
Return
Returns the current instance for method chaining.
MagicObject\DataLabel\PicoDataLabel
Declaration
Package
MagicObject\DataLabelAuthors
- Kamshory
Links
Description
Class representing a data label with annotations for properties and tables.
This class uses annotations to define properties and their metadata.
Constants
Properties
Declaration
Description
Parameters defined in the class annotations.
Declaration
Description
Name of the class.
Methods
Declaration
{
}
Description
Retrieves object information by parsing class and property annotations.
Return
An object containing the table name, columns, default values, and not-null columns.
MagicObject\PicoDataLabel\PicoDataLabels
Declaration
Package
MagicObject\DataLabelAuthors
- Kamshory
Links
Description
Class representing a collection of data labels.
This class allows for the storage and management of multiple data labels.
Properties
Declaration
Description
Collection of data labels.
Methods
Declaration
PicoDataLabel $data
) : self
{
}
Description
Appends a new data label to the collection.
Parameters
The data label to be added.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Generates output based on the collected data labels.
This method processes each data label in the collection.
MagicObject\Exceptions\ClassNotFoundException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class ClassNotFoundException
Custom exception class for handling scenarios where a class could not be found. This exception is typically thrown when attempting to use or instantiate a class that does not exist or is not autoloaded properly. It can be used in situations such as when a class name is misspelled, or the class file is not found in the expected location.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\CurlException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class CurlException
Custom exception class for handling errors related to cURL operations. This exception is typically thrown when there is an issue with a cURL request, such as network failure, timeouts, or invalid responses from the server.
The CurlException class allows you to capture and manage errors related to
cURL requests, providing detailed information about the error message, code,
and the previous exception if any. It extends the built-in Exception class,
and can be caught and handled just like any other exception in PHP.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\EmptyResultException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class EmptyResultException
Custom exception class for handling scenarios where a result is expected but none is returned. This can be useful for database queries or API calls where a missing result should be treated as an exceptional case.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\EntityException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class EntityException
Custom exception class for handling errors related to entity operations. This can include issues such as validation failures, database errors, or other exceptions that occur during entity processing.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\ErrorConnectionException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class ErrorConnectionException
Custom exception class for handling errors related to connection issues. This exception is typically thrown when a connection attempt to a remote service, database, or external resource fails. It can be used in scenarios where the system expects a successful connection but encounters issues, such as timeouts, server unavailability, or invalid credentials.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\FileNotFoundException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class FileNotFoundException
Custom exception class for handling file not found errors. This can be used in scenarios where a required file is missing, such as when attempting to read or access a file that does not exist.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\FindOptionException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class FindOptionException
Custom exception class for handling errors that occur during the process of finding or retrieving options. This exception can be thrown when an expected option is not found, whether in configuration settings, database queries, or other operational contexts.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidAddressException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidAddressException
Custom exception class for handling errors related to invalid addresses. This exception can be thrown when an address fails validation or is found to be improperly formatted. It can be used in scenarios such as address processing in applications that require user input for locations, shipping, or billing addresses.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidAnnotationException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidAnnotationException
Custom exception class for handling errors related to invalid annotations. This exception can be thrown when an annotation is improperly formatted, missing, or fails validation in contexts such as reflection, metadata processing, or any system relying on annotations for configuration.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidClassException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidClassException
Custom exception class for handling errors related to invalid class definitions. This exception can be thrown when a class cannot be instantiated or when a class is found to be improperly defined, potentially during reflection or dynamic class loading operations.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidDatabaseConfiguration
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidDatabaseConfiguration
Custom exception class for handling errors related to invalid database configurations. This exception can be thrown when there are issues with database connection settings, such as incorrect credentials, missing parameters, or invalid configuration values.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidFileFormatException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidFileFormatException
Custom exception class for handling errors related to invalid file formats. This exception can be thrown when a file fails validation based on expected format criteria, such as incorrect file extensions, corrupted files, or improper file structures. It is useful in file upload processes or data import functionalities.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidFilterException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidFilterException
Custom exception class for handling errors related to invalid filters. This exception can be thrown when a filter is improperly defined, fails validation, or cannot be applied in contexts such as data querying, processing, or any operation relying on filters to refine results.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidInputFormatException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidInputFormatException
Custom exception class for handling errors related to invalid input formats. This exception can be thrown when input data fails validation, is improperly structured, or does not meet expected format criteria. It is useful in scenarios such as form submissions, data processing, or API requests where specific input formats are required.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidParameterException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidParameterException
Custom exception class for handling errors related to invalid parameters. This exception can be thrown when a function or method receives parameters that do not meet the expected criteria, such as invalid types, missing required values, or parameters that fall outside of acceptable ranges.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidPolygonException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidPolygonException
Custom exception class for handling errors related to invalid polygon definitions. This exception can be thrown when a polygon fails validation criteria, such as having an insufficient number of vertices, improper angle measurements, or invalid geometric configurations. It is useful in applications involving geometric computations, shape processing, or graphical representations.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidQueryInputException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class InvalidQueryInputException
Thrown when there is an error with the format of annotation attributes applied to a class, property, or method.
This exception is triggered when annotations provided in the code do not meet the expected format or structure. Common scenarios for throwing this exception include:
- Malformed annotation values.
- Missing required parameters in annotations.
-
Incorrect application of annotations to classes, properties, or methods that do not support them.
Example scenarios where this exception may be used:
- A class is annotated with an unsupported attribute or a malformed annotation.
- A property is annotated with an incorrect attribute that does not conform to the expected format.
-
A method receives an unsupported or malformed annotation, resulting in a failure during runtime or reflection processing.
This exception is useful for catching annotation-related errors early in the code execution, allowing developers to quickly address any misconfigurations.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\InvalidReturnTypeException
Declaration
Package
MagicObject\ExceptionsLinks
Description
Class InvalidReturnTypeException
Exception thrown when a function or method returns a value that does not match the expected return type. This can occur in systems with strict typing or when there is a mismatch between a declared return type and the actual returned value during execution. It is particularly useful in frameworks or libraries that rely on reflection or type hinting to ensure correct return types.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Returns the previous exception if it exists, or null if there is no previous exception.
Return
The previous exception
MagicObject\Exceptions\MandatoryTableNameException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class MandatoryTableNameException
Custom exception class for handling errors related to missing mandatory table names in database operations. This exception can be thrown when an operation requires a table name but none is provided, leading to failures in query execution or data manipulation. It is particularly useful in database abstraction layers or ORM implementations.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoColumnMatchException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoColumnMatchException
Custom exception class for handling errors when no columns match during database operations. This exception can be thrown when a query fails to find any columns that satisfy the specified criteria, indicating that the expected data structure does not align with the available columns in the database. It is particularly useful in data mapping or ORM frameworks where column mappings are critical.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoColumnUpdatedException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoColumnUpdatedException
Custom exception class for handling errors when no columns have been updated during a database operation. This exception can be thrown when an update query executes successfully but does not modify any records, indicating that the specified criteria did not match any existing entries. It is particularly useful in scenarios where data integrity and confirmation of changes are critical.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoDatabaseConnectionException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoDatabaseConnectionException
Custom exception class for handling errors related to the absence of a database connection. This exception can be thrown when an application attempts to execute a database operation but fails to establish a connection to the database, possibly due to misconfiguration, network issues, or the database server being down. It is essential for managing connection-related errors in database-driven applications.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoInsertableColumnException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoInsertableColumnException
Custom exception class for handling errors when there are no columns available for insertion during a database operation. This exception can be thrown when an attempt is made to insert data into a database table but the specified columns are either not defined or not allowed for insertion, possibly due to misconfiguration or constraints on the database schema. It is essential for ensuring that data integrity is maintained during insert operations.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoPrimaryKeyDefinedException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoPrimaryKeyDefinedException
Custom exception class for handling errors when a database entity lacks a defined primary key. This exception can be thrown during operations that require a primary key for identifying records, such as updates or deletions. It is crucial for ensuring data integrity and consistency within database operations, especially in ORM frameworks where primary keys are essential for object mapping.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoRecordFoundException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoRecordFoundException
Custom exception class for handling scenarios where a database query does not return any records. This exception is useful in situations where a lookup operation fails to find the requested data, helping to differentiate between successful queries with no results and errors in the query itself. It can be particularly useful in data retrieval operations, ensuring that the calling code can handle the absence of records appropriately.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NotNullColumnException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NotNullColumnException
Custom exception class for handling errors related to database operations where a column defined as NOT NULL is being assigned a null value. This exception can be thrown during insert or update operations, ensuring that the integrity of the database schema is maintained. It is essential for catching issues that may arise from improper data handling or validation before attempting to store records in the database.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NoUpdatableColumnException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NoUpdatableColumnException
Custom exception class for handling scenarios where an attempt is made to update a database record, but no columns are available for updating. This exception is typically thrown during operations where it is essential to have at least one updatable column defined, such as in ORM frameworks or data access layers. It helps to ensure that update operations are valid and that the integrity of the database is maintained.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\NullPointerException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class NullPointerException
Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\UnknownErrorException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class UnknownErrorException
Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\UnsupportedDatabaseException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class UnsupportedDatabaseException
Custom exception class for handling null reference errors in the application. This exception is typically thrown when an operation is attempted on a variable that is null, indicating that the application is trying to access or modify an object or variable that has not been initialized. This exception helps in identifying issues related to null values, ensuring better debugging and error handling.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\Exceptions\YamlException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class YamlException
Custom exception class for handling errors related to YAML parsing or processing. This class extends the base Exception class to provide additional context for YAML-specific errors and maintains a reference to a previous exception if available.
It is useful for scenarios where detailed error handling and chaining of exceptions are required during YAML processing.
Properties
Declaration
Description
Previous exception in the chain (if any).
Methods
Declaration
{
}
Description
Get the previous exception in the chain.
Return
The previous exception if available, or null.
MagicObject\Exceptions\ZeroArgumentException
Declaration
Package
MagicObject\ExceptionsAuthors
- Kamshory
Links
Description
Class ZeroArgumentException
Custom exception class for handling cases where a method or function is called with zero arguments when at least one is expected. This exception extends the built-in InvalidArgumentException to provide more specific error handling for invalid input scenarios. It can help in identifying issues related to argument validation in function calls, ensuring that methods are invoked correctly with the necessary parameters.
Properties
Declaration
Description
Previous exception
Methods
Declaration
{
}
Description
Get the previous exception.
Return
MagicObject\File\PicoDownloadFile
Declaration
Package
MagicObject\FileAuthors
- Kamshory
Links
Description
Class PicoDownloadFile
Facilitates downloading a file, with support for partial content (range requests). This class ensures that requested files exist, handles errors, and supports downloading large files efficiently by sending them in chunks.
Properties
Declaration
Description
@var string The path to the file being downloaded.
Declaration
Description
@var string The filename to be used in the download response.
Methods
Declaration
string $filepath,
string|null $filename = null
)
{
}
Description
PicoDownloadFile constructor.
Parameters
The full path to the file.
The name of the file for download (optional).
Declaration
bool $exit = false
) : bool
{
}
Description
Initiates the download of the file with support for partial content (range requests).
Handles the following:
- Verifies the file exists at the specified path.
- Supports byte range requests for resuming downloads.
- Sends appropriate HTTP headers for file transfer.
- Streams the file to the client in chunks (8 KB by default).
Parameters
Whether to terminate the script after sending the file. Default is false.
Return
Returns true if the entire file was successfully sent, false if only part of the file was sent.
Declaration
{
}
Description
Checks if the file exists.
Return
True if the file exists, false otherwise.
Declaration
int $statusCode,
string $message,
int|null $fileSize = null
)
{
}
Description
Sends an error response with the given status code and message.
Parameters
The HTTP status code.
The error message.
The file size to include in the Content-Range header (optional).
Declaration
int $fileSize
) : array
{
}
Description
Determines the byte range from the HTTP_RANGE header.
Parameters
The size of the file.
Return
The start and end byte positions for the range.
Declaration
int $start,
int $end,
int $fileSize
) : bool
{
}
Description
Checks if the byte range is valid.
Parameters
The start byte.
The end byte.
The total size of the file.
Return
True if the range is invalid.
Declaration
int $start,
int $end,
int $fileSize
)
{
}
Description
Sends the appropriate HTTP headers for the download.
Parameters
The start byte.
The end byte.
The total size of the file.
Declaration
resource $fp,
int $start,
int $end
)
{
}
Description
Streams the file to the client in chunks.
Parameters
The file pointer.
The start byte.
The end byte.
MagicObject\File\PicoUploadFile
Declaration
Package
MagicObject\FileAuthors
- Kamshory
Links
Description
Class representing an upload file tool.
This class is designed to handle uploaded files. All attributes in this class are read-only.
Properties
Declaration
Description
Mapping of uploaded file names to their keys.
Declaration
Description
Array of uploaded file containers.
Methods
Declaration
{
}
Description
Constructor.
Initializes the mapping of uploaded file names and populates the values.
Declaration
string $method,
array $arguments
) : mixed
{
}
Description
Magic method to handle dynamic getter calls.
This method enables the retrieval of property values through dynamically named getter methods. It specifically handles methods that start with the prefix "get". When a getter method is called, the method extracts the property name from the method name, converts it to camel case, and retrieves the corresponding value from an internal storage.
If the requested property exists, its value is returned. If it does not exist,
an instance of PicoUploadFileContainer is returned as an empty container.
Supported dynamic getter:
get<FieldName>: Retrieves the value associated with the specified field. For example, calling$obj->getFile()would:- Extract the field name
filefrom the method name. - Look up the camel-cased key in the internal storage.
- Return the associated value or a new
PicoUploadFileContainerif the value is not found.
- Extract the field name
Parameters
The name of the method being called, expected to start with "get".
The arguments passed to the method; typically unused in getter methods.
Return
The value of the requested property if it exists; otherwise, an instance of PicoUploadFileContainer.
Declaration
string $name
) : PicoUploadFileContainer
{
}
Description
Get an uploaded file by parameter name.
Parameters
The parameter name.
Return
An instance of the uploaded file container or an empty container.
Declaration
string $name
) : PicoUploadFileContainer
{
}
Description
Magic method to handle dynamic property access.
Parameters
The name of the property being accessed.
Return
An instance of the uploaded file container or an empty container.
Declaration
string $name
) : bool
{
}
Description
Check if an uploaded file exists for the given parameter name.
Parameters
The parameter name.
Return
True if the file exists; otherwise, false.
Declaration
{
}
Description
Initialize the mapping of uploaded file names to their keys.
Return
Declaration
{
}
Description
Convert the object to a string representation for debugging.
Return
JSON-encoded string of the uploaded file data.
MagicObject\File\PicoUploadFileContainer
Declaration
Package
MagicObject\FileAuthors
- Kamshory
Links
Description
Class representing a container for uploaded files.
This class manages the uploaded file information and provides methods to handle single or multiple file uploads.
Properties
Declaration
Description
Array to store information about uploaded files.
Methods
Declaration
array|null $file = null
)
{
}
Description
Constructor.
Initializes the container with uploaded file data.
Parameters
An associative array containing file upload information.
Declaration
{
}
Description
Checks if multiple files were uploaded.
Return
True if multiple files were uploaded; otherwise, false.
Declaration
int $index
) : bool
{
}
Description
Checks if a specific file exists in the upload.
Parameters
The index of the uploaded file.
Return
True if the file exists; otherwise, false.
Declaration
{
}
Description
Gets the total number of uploaded files.
Return
The number of files uploaded.
Declaration
{
}
Description
Retrieves all uploaded files.
Return
An array of PicoUploadFileItem objects representing uploaded files.
Declaration
int $index
) : array
{
}
Description
Gets information about a specific uploaded file.
Parameters
The index of the uploaded file.
Return
An associative array containing information about the uploaded file.
Declaration
{
}
Description
Converts the object to a string representation.
Return
A JSON-encoded string of the uploaded file information.
MagicObject\File\PicoUploadFileItem
Declaration
Package
MagicObject\FileAuthors
- Kamshory
Links
Description
Class representing an uploaded file item.
This class manages the information of an uploaded file and provides methods to interact with the file, such as copying or moving it to a destination path.
Properties
Declaration
Description
Array to store uploaded file information.
Methods
Declaration
array $file
)
{
}
Description
Constructor.
Initializes the PicoUploadFileItem with file data.
Parameters
An associative array containing file upload information.
Throws
if the provided file data is invalid.
Declaration
string $path
) : bool
{
}
Description
Copies the uploaded file to a specified destination path.
Parameters
The target path where the file will be copied.
Return
True on success; otherwise, false.
Throws
if the temporary file is not found.
Declaration
string $path
) : bool
{
}
Description
Moves the uploaded file to a specified destination path.
Parameters
The target path where the file will be moved.
Return
True on success; otherwise, false.
Throws
if the temporary file is not found.
Declaration
{
}
Description
Gets the temporary file name.
Return
The temporary file name or null if not set.
Declaration
{
}
Description
Gets the original file name.
Return
The original file name or null if not set.
Declaration
{
}
Description
Gets the error associated with the file upload.
Return
The error code or null if not set.
Declaration
{
}
Description
Gets the size of the uploaded file.
Return
The file size in bytes; returns 0 if not set.
Declaration
{
}
Description
Gets the MIME type of the uploaded file.
Return
The MIME type or null if not set.
MagicObject\Generator\PicoColumnGenerator
Declaration
Package
MagicObject\GeneratorAuthors
- Kamshory
Links
Description
Class for generating column information from a database.
This class provides methods to retrieve a list of columns for a specified database table.
Methods
Declaration
PicoDatabase $database,
string $picoTableName
) : array
{
}
Description
Get the list of columns from a specified database table.
Parameters
The database connection instance.
The name of the table to retrieve columns from.
Return
An array of column names or an empty array if not applicable.
MagicObject\Generator\PicoDatabaseDump
Declaration
Package
MagicObject\GeneratorAuthors
- Kamshory
Links
Description
Database dump class for managing and generating SQL statements for table structures.
Properties
Declaration
Description
Table information
Declaration
Description
Table name
Declaration
Description
Columns
Methods
Declaration
MagicObject $entity,
string $databaseType,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string $engine = 'InnoDB',
string $charset = 'utf8mb4'
) : string
{
}
Description
Dump the structure of a table for the specified entity.
Parameters
Entity to be dumped
Target database type
Add DROP TABLE IF EXISTS before create table
Add IF NOT EXISTS on create table
Storage engine (for MariaDB and MySQL)
Default charset
Return
SQL statement for creating table structure
Declaration
PicoTableInfo $tableInfo,
string $databaseType,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string $engine = 'InnoDB',
string $charset = 'utf8mb4'
) : string
{
}
Description
Dump the structure of a specified table.
Parameters
Table information
Database type
Flag to add CREATE IF NOT EXISTS
Flag to add DROP IF EXISTS
Database engine
Charset
Return
SQL statement for creating table structure
Declaration
MagicObject $entity
) : PicoTableInfo|null
{
}
Description
Get the table information for the specified entity.
Parameters
Entity
Return
Table information or null if entity is null
Declaration
string $query,
string $lastColumn,
string $databaseType
) : string
{
}
Description
Update the query for adding a column to a table.
Parameters
Query string
Last column name
Database type
Return
Updated query string
Declaration
string $query,
array $entityColumn
) : string
{
}
Description
Update the query to set a column as nullable.
Parameters
Query string
Entity column information
Return
Updated query string
Declaration
string $query,
array $entityColumn
) : string
{
}
Description
Update the query to set a default value for a column.
Parameters
Query string
Entity column information
Return
Updated query string
Declaration
MagicObject|MagicObject[] $entity,
PicoDatabase|null $database = null,
bool $createIfNotExists = false,
bool $dropIfExists = false,
bool $forceCreateNewTable = false
) : string[]
{
}
Description
Create an ALTER TABLE ADD COLUMN query for the specified entity or entities.
This method generates SQL queries to add new columns to a table. It supports adding columns
from either a single entity or an array of entities. Depending on whether a single entity or
multiple entities are provided, the method delegates query generation to different helper methods.
If the $forceCreateNewTable flag is set to true, the method will generate a CREATE TABLE query
instead of an ALTER TABLE query, effectively creating a new table with the specified columns.
Parameters
A single entity or an array of entities representing the columns to be added.
The database connection used to fetch the current table schema. If null,
Flag indicating whether to generate a CREATE TABLE query if the table does not exist.
Flag indicating whether to generate a DROP TABLE query if the table already exists,
Flag indicating whether to generate a CREATE TABLE query instead of ALTER TABLE,
Return
An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns.
Declaration
PicoDatabase|null $database,
MagicObject[] $entities
) : PicoDatabase
{
}
Description
Get the database connection.
Parameters
Database connection
Entities
Return
Database connection
Declaration
PicoDatabase $database
) : string
{
}
Description
Get the database type.
Parameters
Database connection
Return
Database type
Declaration
string|null $tableName,
PicoTableInfo $tableInfo
) : string
{
}
Description
Get the table name.
Parameters
Table name
Table information
Return
Table name
Declaration
string $tableName,
string $columnName,
string $columnType
) : string
{
}
Description
Create an ALTER TABLE query to add a column.
Parameters
Table name
Column name
Column type
Return
SQL ALTER TABLE query
Declaration
MagicObject[] $entities
) : string[]
{
}
Description
Get a list of column names from multiple entities.
This method retrieves the table information for each entity, extracts the columns, and merges them into a single list.
Parameters
Array of entities to process.
Return
List of column names from all entities.
Declaration
MagicObject[] $entities,
string|null $tableName = null,
PicoDatabase|null $database = null,
bool $createIfNotExists = false,
bool $dropIfExists = false,
bool $forceCreateNewTable = false
) : string[]
{
}
Description
Create a list of ALTER TABLE ADD COLUMN queries from multiple entities.
This method generates SQL queries to add new columns to an existing table based on the provided entities.
It checks the current database schema and compares it with the provided entity information, generating the
necessary ALTER TABLE queries. If columns already exist in the database, they will be skipped unless the
forceCreateNewTable flag is set to true, in which case a CREATE TABLE query will be generated to create
the table (and columns) from scratch, even if the columns already exist.
Parameters
An array of entity objects representing the columns to be added. Each entity contains
The name of the table to alter. If null, the table name will be derived from the entities.
The database connection used to fetch the current table schema. If null, it will
Flag indicating whether a CREATE TABLE query should be generated if the table does not exist.
Flag indicating whether a DROP TABLE query should be generated if the table already exists,
Flag indicating whether to generate a CREATE TABLE query instead of an ALTER TABLE query.
Return
An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns. Each query is a string
Declaration
MagicObject $entity,
bool $forceCreateNewTable = false
) : string[]
{
}
Description
Create a list of ALTER TABLE ADD COLUMN queries or a CREATE TABLE query from a single entity.
This method generates SQL queries to add new columns to a table based on the provided entity.
It compares the current database schema with the entity's column definitions. If the columns do not already exist,
it generates the necessary ALTER TABLE queries. However, if the forceCreateNewTable flag is set to true,
a CREATE TABLE query will be generated instead of ALTER TABLE, effectively creating the table and columns from scratch
even if the columns already exist in the database.
Parameters
The entity representing the table and its columns to be added.
Flag indicating whether to generate a CREATE TABLE query, even if the table and
Return
An array of SQL queries (either ALTER TABLE or CREATE TABLE) to add the columns. Each query
Declaration
string[] $queryAlter,
PicoTableInfoExtended $tableInfo,
string $tableName,
string[] $createdColumns
) : string[]
{
}
Description
Add primary key constraints to the ALTER TABLE queries.
Parameters
Existing ALTER TABLE queries
Table information
Table name
List of created columns
Return
Updated ALTER TABLE queries
Declaration
string[] $queryAlter,
PicoTableInfoExtended $tableInfo,
string $tableName,
string[] $createdColumns,
string $databaseType
) : string[]
{
}
Description
Add auto-increment functionality to specified columns.
Parameters
Existing ALTER TABLE queries
Table information
Table name
List of created columns
Database type
Return
Updated ALTER TABLE queries
Declaration
PicoTableInfo $tableInfo
) : string[]
{
}
Description
Get the auto-increment keys from table information.
Parameters
Table information
Return
List of auto-increment keys
Declaration
MagicObject[] $entities
) : PicoTableInfoExtended
{
}
Description
Merge multiple entities' table information.
Parameters
Entities
Return
Merged table information
Declaration
MagicObject[] $entities
) : PicoTableInfoExtended
{
}
Description
Get merged table information from multiple entities.
Parameters
Entities
Return
Merged table information
Declaration
MagicObject|PicoPageData $data,
string $databaseType,
MagicObject|null $entity = null,
int $maxRecord = 100,
callable|null $callbackFunction = null
) : string
{
}
Description
Dumps data into SQL format.
This method processes the provided data and converts it into SQL format suitable for the specified database type. It requires a model instance to retrieve table information if not already set.
WARNING: Use a different instance to dump different entities to avoid conflicts.
Parameters
Data to be dumped into SQL format.
Target database type (e.g., MySQL, MariaDB).
Optional model instance used to retrieve table information
Maximum number of records to process in a single query (default is 100).
Optional callback function to process the generated SQL
Return
SQL dump as a string; returns an empty string for unsupported database types.
MagicObject\Generator\PicoDtoGenerator
Declaration
Package
MagicObject\GeneratorAuthors
- Kamshory
Links
Description
DTO generator for creating Data Transfer Objects (DTOs) from database tables.
This class helps in generating DTOs that can be used for transferring data via APIs or for serialization into files or databases.
Properties
Declaration
Description
Database connection instance.
Declaration
Description
Base directory for saving generated DTO files.
Declaration
Description
Base namespace for the generated DTOs.
Declaration
Description
Table name to generate DTO for.
Declaration
Description
Name of the entity associated with the DTO.
Declaration
Description
Name of the DTO being generated.
Declaration
Description
Base namespace for the entity.
Declaration
Description
Flag to indicate whether to prettify the output.
Methods
Declaration
PicoDatabase $database,
string $baseDir,
string $tableName,
string $baseNamespaceDto,
string $dtoName,
string $baseNamespaceEntity,
string|null $entityName = null,
bool $prettify = false
)
{
}
Description
Constructor for the DTO generator.
Parameters
Database connection
Base directory for generated files
Table name for DTO generation
Base namespace for DTOs
Name of the DTO
Base namespace for the entity
Name of the entity (optional)
Flag to prettify output (default: false)
Declaration
array $typeMap,
string $columnName,
string $columnType,
bool $prettifyLabel = true
) : string
{
}
Description
Create a property with appropriate documentation.
This method generates a PHP property with a docblock based on the provided column name and type.
The docblock includes annotations like @Label to describe the property and @var to specify the
data type of the property. It is used to automatically generate well-documented properties based
on database column information.
Parameters
Mapping of database types to PHP types (e.g., 'int' => 'integer').
Name of the column from the database.
Type of the column from the database (e.g., 'varchar', 'int').
Whether to modify the column name into a more readable label (default is true).
Return
PHP code for the property with a docblock, including the appropriate annotations like
Declaration
string $name,
bool $prettifyLabel = true
) : string
{
}
Description
Get a descriptive name for the property based on the column name. The column name is converted to a formatted property name, where each part of the column name (split by underscores) is capitalized. Special cases such as "Id" and "Ip" are handled to be formatted as "ID" and "IP", respectively.
Parameters
Original column name (e.g., 'user_id', 'user_ip')
Whether to replace 'Id' with 'ID' and 'Ip' with 'IP'
Return
Formatted property name (e.g., 'User ID', 'User IP')
Declaration
array $typeMap,
string $columnType
) : string
{
}
Description
Determine the PHP data type corresponding to the column type.
Parameters
Mapping of database types to PHP types
Database column type
Return
Corresponding PHP data type
Declaration
string $picoTableName,
array $rows
) : string
{
}
Description
Create a static method to construct the DTO from the entity.
Parameters
Table name
Data rows from the database
Return
PHP code for the valueOf method
Declaration
{
}
Description
Get a mapping of database types to PHP types.
Return
Associative array of type mappings
Declaration
{
}
Description
Generate the DTO and save it to a file.
Return
Result of file write operation (number of bytes written or false on failure)
MagicObject\Generator\PicoEntityGenerator
Declaration
Package
MagicObject\GeneratorAuthors
- Kamshory
Links
Description
PicoEntityGenerator is an entity generator for automatically generating PHP code. This class is optimized for the MariaDB database. Users must provide appropriate parameters so that the entity class can be directly used in the application.
Constants
Properties
Declaration
Description
Database connection instance.
Declaration
Description
Base directory for generated files.
Declaration
Description
Base namespace for the entity classes.
Declaration
Description
Table name for which the entity is generated.
Declaration
Description
Name of the entity being generated.
Declaration
Description
Flag indicating whether to prettify the output.
Methods
Declaration
PicoDatabase $database,
string $baseDir,
string $tableName,
string $baseNamespace,
string|null $entityName = null,
bool $prettify = false
)
{
}
Description
Constructor for the PicoEntityGenerator class.
Parameters
Database connection
Base directory for generated files
Table name for entity generation
Base namespace for the entity classes
Name of the entity (optional)
Flag to prettify output (default: false)
Declaration
array $typeMap,
array $columnMap,
array $row,
string[]|null $nonupdatables = null,
bool $prettifyLabel = true
) : string
{
}
Description
Generates a PHP property with a docblock based on database column metadata.
This method creates a property for a PHP class, including annotations such as @Id, @GeneratedValue,
@NotNull, and @Column, derived from the given database column details. It supports column attributes
like primary key, auto-increment, nullable, and default value, and provides type mappings based on the
provided database-to-PHP type mappings.
Parameters
Database-to-PHP type mappings (e.g., 'int' => 'integer').
Database column-to-type mappings (e.g., 'int' => 'INTEGER').
Column metadata from the database (e.g., from information_schema.columns).
List of non-updatable columns, or null if none.
Whether to convert column names to human-readable labels (default is true).
Return
PHP code for the property with a docblock, ready to be inserted into a class.
Declaration
string $name,
bool $prettifyLabel = true
) : string
{
}
Description
Get a descriptive name for the property based on the column name. The column name is converted to a formatted property name, where each part of the column name (split by underscores) is capitalized. Special cases such as "Id" and "Ip" are handled to be formatted as "ID" and "IP", respectively.
Parameters
Original column name (e.g., 'user_id', 'user_ip')
Whether to replace 'Id' with 'ID' and 'Ip' with 'IP'
Return
Formatted property name (e.g., 'User ID', 'User IP')
Declaration
array $typeMap,
string $columnType
) : string
{
}
Description
Get the corresponding PHP data type based on the column type.
Parameters
Mapping of database types to PHP types
Database column type
Return
Corresponding PHP data type
Declaration
array $typeMap,
string $columnType
) : string
{
}
Description
Get the corresponding PHP data type based on the column type.
Parameters
Mapping of database types to PHP types
Database column type
Return
Corresponding PHP data type
Declaration
string $str
) : int
{
}
Description
Get the length of the column based on its definition.
Parameters
Column definition containing length
Return
Length of the column
Declaration
{
}
Description
Get a mapping of database types to PHP types for MySQL, PostgreSQL, and SQLite.
This method returns an associative array that maps common database column types from MySQL, PostgreSQL, and SQLite to their corresponding PHP types. This mapping is useful for handling database type conversions when interacting with data in PHP.
The array provides mappings for numeric types, string types, boolean types, date/time types, and special cases such as JSON and UUID. It helps in ensuring proper handling of database types across different database systems.
Return
Associative array of type mappings where the keys are database column types
Declaration
{
}
Description
Get a mapping of database column types to MySQL equivalents.
Provides a conversion map from various database column types to MySQL-compatible column types, useful for data migrations or type compatibility.
Return
Associative array with column types from other databases mapped to MySQL types.
Declaration
string $targetDb
) : array
{
}
Description
Get a mapping of database column types to target database equivalents.
Converts column types from one database (MySQL, PostgreSQL, SQLite) to another, supporting data migrations and compatibility.
Parameters
The target database type ('mysql', 'postgresql', or 'sqlite').
Return
Associative array of column types from other databases mapped to the target database types.
Declaration
string[]|null $nonupdatables = null,
bool $prettifyLabel = true
) : int|false
{
}
Description
Generates an entity class based on database table metadata and saves it to a file.
This method creates a PHP class that maps to a database table, including properties for each column.
It supports ORM annotations (e.g., @Entity, @Table, @JSON) and handles non-updatable columns.
Optionally, it can prettify property names for human readability.
Parameters
List of non-updatable columns, or null if none.
Whether to prettify column names into human-readable labels (default is true).
Return
The number of bytes written to the file, or false on failure.
MagicObject\Geometry\Area
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class Area
Represents a geometric area defined by various shapes such as rectangles, triangles, polygons, and circles. This class encapsulates properties related to the shape, its coordinates, and any associated attributes or hyperlinks. It also provides methods to calculate coordinates based on the shape type, apply zoom factors, and generate an HTML representation for use in maps or similar applications.
Properties
Declaration
Description
Shape type of the area.
Declaration
Description
Coordinates defining the shape.
Declaration
Description
Hyperlink reference associated with the area.
Declaration
Description
Additional attributes for the area.
Declaration
Description
Zoom factor for the area.
Methods
Declaration
mixed $object,
float $zoom = 1,
string|null $href = null,
string[]|null $attributes = null
)
{
}
Description
Constructor for the Area class.
Parameters
One of Rectangle, Triangle, Polygon, or Circle
Zoom factor (default: 1)
Hyperlink reference (optional)
Additional attributes (optional)
Declaration
Rectangle $object
) : float[]
{
}
Description
Get coordinates from a rectangle.
Parameters
Rectangle object
Return
Coordinates of the rectangle
Declaration
Triangle $object
) : float[]
{
}
Description
Get coordinates from a triangle.
Parameters
Triangle object
Return
Coordinates of the triangle
Declaration
Polygon $object
) : float[]
{
}
Description
Get coordinates from a polygon.
Parameters
Polygon object
Return
Coordinates of the polygon
Declaration
Circle $object
) : float[]
{
}
Description
Get coordinates from a circle.
Parameters
Circle object
Return
Coordinates of the circle
Declaration
float $zoom = 1
) : float[]
{
}
Description
Get coordinates with optional zoom factor.
Parameters
Zoom factor (default: 1)
Return
Adjusted coordinates
Declaration
{
}
Description
Generate HTML representation of the area.
Return
HTML string for the area
Declaration
{
}
Description
Convert the area object to a string.
Return
HTML representation of the area
Declaration
{
}
Description
Get the current zoom factor.
Return
Zoom factor
Declaration
float $zoom
) : self
{
}
Description
Set the zoom factor.
Parameters
Zoom factor
Return
Returns the current instance for method chaining.
MagicObject\Geometry\Circle
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class Circle
Represents a circle defined by a center point and a radius. This class provides methods to calculate the circle's circumference and area, based on its radius. The circle is defined by its center coordinates (x, y) and its radius (r).
Properties
Declaration
Description
Center point of the circle.
Declaration
Description
x coordinate of the circle's center.
Declaration
Description
y coordinate of the circle's center.
Declaration
Description
Radius of the circle.
Methods
Declaration
float $x,
float $y,
float $r
)
{
}
Description
Constructor to initialize the Circle with x, y, and r.
Parameters
x coordinate of the center
y coordinate of the center
Radius of the circle
Declaration
{
}
Description
Get the circumference of the circle.
Return
Circumference of the circle
Declaration
{
}
Description
Get the area of the circle.
Return
Area of the circle
MagicObject\Geometry\LatBounds
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class LatBounds
Represents a latitude bounding box defined by southwestern and northeastern latitude values. This class provides functionality to manage and calculate properties of latitude bounds, including checking for containment, intersections, and equality with other latitude bounds.
Properties
Declaration
Description
@var float The southwestern latitude value.
Declaration
Description
@var float The northeastern latitude value.
Methods
Declaration
float $swLat,
float $neLat
)
{
}
Description
LatBounds constructor.
Parameters
The southwestern latitude.
The northeastern latitude.
Declaration
{
}
Description
Get the southwestern latitude.
Return
The southwestern latitude.
Declaration
{
}
Description
Get the northeastern latitude.
Return
The northeastern latitude.
Declaration
{
}
Description
Calculate the midpoint latitude between the southwestern and northeastern latitudes.
Return
The midpoint latitude.
Declaration
{
}
Description
Check if the latitude bounds are empty (i.e., invalid).
Return
True if the bounds are empty, false otherwise.
Declaration
LatBounds $latBounds
) : bool
{
}
Description
Determine if this LatBounds intersects with another LatBounds.
Parameters
The other LatBounds to check for intersection.
Return
True if there is an intersection, false otherwise.
Declaration
LatBounds $latBounds
) : bool
{
}
Description
Check if this LatBounds is equal to another LatBounds within a certain margin of error.
Parameters
The other LatBounds to compare.
Return
True if they are equal, false otherwise.
Declaration
float $lat
) : bool
{
}
Description
Check if a given latitude is contained within the bounds.
Parameters
The latitude to check.
Return
True if the latitude is contained, false otherwise.
Declaration
float $lat
)
{
}
Description
Extend the bounds to include a new latitude.
If the bounds are empty, the latitude becomes both the southwestern and northeastern bounds. If the latitude is less than the southwestern bound, it updates the southwestern bound. If the latitude is greater than the northeastern bound, it updates the northeastern bound.
Parameters
The latitude to extend the bounds with.
MagicObject\Geometry\LatLng
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class LatLng
Represents a geographical point defined by latitude and longitude values. This class provides methods to manage and manipulate geographic coordinates, including equality checks and string representations.
Properties
Declaration
Description
@var float The latitude value.
Declaration
Description
@var float The longitude value.
Methods
Declaration
float $lat,
float $lng,
bool $noWrap = false
)
{
}
Description
LatLng constructor.
Parameters
The latitude value.
The longitude value.
Whether to wrap the longitude value.
Throws
If the latitude or longitude is not a valid float.
Declaration
{
}
Description
Get the latitude value.
Return
The latitude.
Declaration
{
}
Description
Get the longitude value.
Return
The longitude.
Declaration
LatLng $latLng
) : bool
{
}
Description
Check if this LatLng is equal to another LatLng object within a certain margin of error.
Parameters
The LatLng object to compare.
Return
True if they are equal, false otherwise.
Declaration
{
}
Description
Convert the LatLng object to a string representation.
Return
The string representation of the LatLng in the format "(lat, lng)".
Declaration
int $precision = 6
) : string
{
}
Description
Convert the LatLng object to a URL-friendly string value.
Parameters
The number of decimal places to round to (default: 6).
Return
The latitude and longitude values as a string.
MagicObject\Geometry\LatLngBounds
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class LatLngBounds
Represents a bounding box defined by southwest and northeast LatLng objects.
Properties
Declaration
Description
@var LatBounds The latitude bounds of the bounding box.
Declaration
Description
@var LngBounds The longitude bounds of the bounding box.
Methods
Declaration
LatLng|null $latLngSw = null,
LatLng|null $tatLngNe = null
)
{
}
Description
LatLngBounds constructor.
Parameters
The southwestern LatLng object.
The northeastern LatLng object.
Throws
If the provided LatLng objects are invalid.
Declaration
{
}
Description
Get the latitude bounds.
Return
The latitude bounds of the bounding box.
Declaration
{
}
Description
Get the longitude bounds.
Return
The longitude bounds of the bounding box.
Declaration
{
}
Description
Get the center point of the bounding box.
Return
The center point as a LatLng object.
Declaration
{
}
Description
Check if the bounding box is empty.
Return
True if the bounding box is empty, false otherwise.
Declaration
{
}
Description
Get the southwestern corner of the bounding box.
Return
The southwestern corner as a LatLng object.
Declaration
{
}
Description
Get the northeastern corner of the bounding box.
Return
The northeastern corner as a LatLng object.
Declaration
{
}
Description
Get the span of the bounding box as a LatLng object.
Return
The span defined by the latitude and longitude differences.
Declaration
{
}
Description
Convert the bounding box to a string representation.
Return
The string representation of the bounding box.
Declaration
int $precision = 6
) : string
{
}
Description
Convert the bounding box to a URL-friendly string value.
Parameters
The number of decimal places to round to.
Return
The southwest and northeast corner values as a string.
Declaration
LatLngBounds $latLngBounds
) : bool
{
}
Description
Check if this LatLngBounds is equal to another LatLngBounds object.
Parameters
The LatLngBounds object to compare.
Return
True if they are equal, false otherwise.
Declaration
LatLngBounds $latLngBounds
) : bool
{
}
Description
Check if this LatLngBounds intersects with another LatLngBounds.
Parameters
The LatLngBounds to check for intersection.
Return
True if they intersect, false otherwise.
Declaration
LatLngBounds $latLngBounds
) : $this
{
}
Description
Extend this bounding box to include another LatLngBounds.
Parameters
The LatLngBounds to extend with.
Return
The current instance for method chaining.
Declaration
LatLng $latLng
) : bool
{
}
Description
Check if this LatLngBounds contains a specific LatLng point.
Parameters
The LatLng point to check for containment.
Return
True if the point is contained, false otherwise.
Declaration
LatLng $latLng
) : $this
{
}
Description
Extend the bounding box to include a new LatLng point.
Parameters
The LatLng point to extend with.
Return
The current instance for method chaining.
MagicObject\Geometry\Line
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a Line with two Point objects.
This class defines a Line in a 2D space represented by two endpoints, Point A and Point B. It provides methods to calculate the length of the line and ensure the endpoints are valid Point instances.
Properties
Declaration
Description
Point A.
Declaration
Description
Point B.
Methods
Declaration
Point $a,
Point $b
)
{
}
Description
Constructor to initialize the Line with two Point objects.
Parameters
Point A.
Point B.
Throws
If the parameters are not instances of Point.
Declaration
{
}
Description
Method to calculate the length of the line.
This method calculates the Euclidean distance between Point A and Point B.
Return
The length of the line between Point A and Point B.
MagicObject\Geometry\LngBounds
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class LngBounds
Represents a longitudinal bounding range defined by southwest and northeast longitude values.
Properties
Declaration
Description
@var float The southwestern longitude value.
Declaration
Description
@var float The northeastern longitude value.
Methods
Declaration
float $swLng,
float $neLng
)
{
}
Description
LngBounds constructor.
Parameters
The southwestern longitude value.
The northeastern longitude value.
Declaration
{
}
Description
Get the southwestern longitude.
Return
The southwestern longitude value.
Declaration
{
}
Description
Get the northeastern longitude.
Return
The northeastern longitude value.
Declaration
{
}
Description
Get the midpoint of the longitude bounds.
Return
The midpoint longitude value.
Declaration
{
}
Description
Check if the bounds are empty.
Return
True if the bounds are empty, false otherwise.
Declaration
LngBounds $lngBounds
) : bool
{
}
Description
Check if this LngBounds intersects with another LngBounds.
Parameters
The LngBounds to check for intersection.
Return
True if they intersect, false otherwise.
Declaration
LngBounds $lngBounds
) : bool
{
}
Description
Check if this LngBounds is equal to another LngBounds.
Parameters
The LngBounds object to compare.
Return
True if they are equal, false otherwise.
Declaration
float $lng
) : bool
{
}
Description
Check if a given longitude is contained within the bounds.
Parameters
The longitude to check.
Return
True if the longitude is contained, false otherwise.
Declaration
float $lng
) : void
{
}
Description
Extend the bounds to include a new longitude.
Parameters
The longitude to extend the bounds with.
Return
MagicObject\Geometry\Map
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a Map containing multiple Areas.
This class manages a collection of Area objects, allowing for the addition and retrieval of areas. It can be initialized with an optional array of Area objects.
Properties
Declaration
Description
Areas in the map.
Methods
Declaration
Area[]|null $areas = null
)
{
}
Description
Constructor to initialize the Map with optional areas.
Parameters
An array of Area objects to initialize the map with.
Declaration
Area $area
) : self
{
}
Description
Add an area to the map.
This method appends a new Area object to the map's collection of areas.
Parameters
Area to add
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get all areas in the map.
This method returns an array of Area objects contained in the map.
Return
An array of Area objects
MagicObject\Geometry\NodeAttribute
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing node attributes.
This class stores a collection of attribute values associated with a node. It provides methods for initialization and converting the attributes to a string representation, suitable for use in contexts such as HTML attributes.
Properties
Declaration
Description
Values of the node attributes.
Methods
Declaration
string[] $values
)
{
}
Description
Constructor to initialize the NodeAttribute with values.
Parameters
An array of attribute values.
Declaration
{
}
Description
Convert the node attributes to a string representation.
This method returns the attributes in a format suitable for inclusion in HTML tags, where each attribute is represented as key="value".
Return
A string representation of the node attributes.
MagicObject\Geometry\Point
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a Point with x and y coordinates.
This class defines a Point in a 2D Cartesian coordinate system, allowing for the representation of its position and the calculation of distances to other Points.
Properties
Declaration
Description
X coordinate.
Declaration
Description
Y coordinate.
Methods
Declaration
float $x,
float $y
)
{
}
Description
Constructor to initialize the Point with x and y coordinates.
Parameters
X coordinate.
Y coordinate.
Declaration
Point $p
) : float
{
}
Description
Calculate the distance between this Point and another Point.
This method computes the Euclidean distance between the current Point and another Point provided as an argument.
Parameters
Another Point.
Return
The distance between the two Points.
Throws
If the argument is not of type Point.
Declaration
Point $p
) : float
{
}
Description
Calculate the distance between this Point and another Point.
This method serves as an alias to distanceFrom for better readability.
Parameters
Another Point.
Return
The distance between the two Points.
MagicObject\Geometry\Polygon
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a polygon defined by a series of points.
This class allows for the creation and manipulation of polygons, including adding points, clearing the polygon, and calculating its area and circumference.
Properties
Declaration
Description
Points that make up the polygon.
Methods
Declaration
Point[] $points = array ( )
)
{
}
Description
Constructor to initialize the Polygon with an array of Points.
Parameters
Initial points for the polygon.
Declaration
Point $point
) : self
{
}
Description
Add a point to the polygon.
Parameters
Point to add.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Clear all points from the polygon.
This method removes all points currently defined for the polygon.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Calculate the area of the polygon using the Shoelace formula.
Return
The area of the polygon.
Throws
If the polygon has fewer than 3 points.
Declaration
{
}
Description
Calculate the circumference of the polygon.
This method computes the total length of the polygon's edges.
Return
The circumference of the polygon.
Throws
If the polygon has fewer than 2 points.
Declaration
{
}
Description
Get the points of the polygon.
Return
An array of Point objects that define the polygon.
MagicObject\Geometry\Rectangle
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a rectangle defined by two Point objects.
This class represents a rectangle using its bottom-left and top-right corner points. It provides methods to calculate the area and circumference (perimeter) of the rectangle by utilizing a Polygon representation of the rectangle's corners.
Properties
Declaration
Description
Bottom-left corner point of the rectangle.
Declaration
Description
Top-right corner point of the rectangle.
Declaration
Description
Polygon representation of the rectangle.
Methods
Declaration
Point $a,
Point $b
)
{
}
Description
Constructor to initialize the Rectangle with two Point objects.
Parameters
Bottom-left corner point.
Top-right corner point.
Declaration
{
}
Description
Calculate the area of the rectangle.
Return
The area of the rectangle.
Throws
If the polygon is invalid.
Declaration
{
}
Description
Get the circumference (perimeter) of the rectangle.
Return
The circumference of the rectangle.
Throws
If the polygon is invalid.
MagicObject\Geometry\SphericalGeometry
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Static class SphericalGeometry
Provides utility functions for computing geodesic angles, distances, areas, and other spherical geometry calculations.
Constants
Methods
Declaration
{
}
Description
Get the Earth's radius.
Return
The Earth's radius in meters.
Declaration
LatLng $latLng,
int|float $radius
) : LatLngBounds
{
}
Description
Computes a bounding rectangle (LatLngBounds instance) from a point and a given radius.
Reference: http://www.movable-type.co.uk/scripts/latlong-db.html
Parameters
The center point as a LatLng object.
The radius in meters.
Return
The computed bounding rectangle.
Declaration
LatLng $fromLatLng,
LatLng $toLatLng
) : float
{
}
Description
Computes the heading from one LatLng to another.
Parameters
The starting LatLng.
The destination LatLng.
Return
The heading in degrees from the starting point to the destination.
Declaration
LatLng $fromLatLng,
float $distance,
float $heading
) : LatLng
{
}
Description
Computes a new LatLng based on a starting point, distance, and heading.
Parameters
The starting LatLng.
The distance to move, in meters.
The direction to move, in degrees.
Return
The new LatLng after the offset.
Declaration
object $point,
object $polygon
) : bool
{
}
Description
Determines whether a point is contained within a polygon.
Parameters
A point object with x() and y() methods for longitude and latitude.
A polygon object with an exteriorRing() method.
Return
True if the point is inside the polygon, false otherwise.
Declaration
LatLng $fromLatLng,
LatLng $toLatLng,
float $fraction
) : LatLng
{
}
Description
Interpolates between two LatLng points based on a fraction.
Parameters
The starting LatLng.
The ending LatLng.
A fraction between 0 and 1.
Return
The interpolated LatLng.
Declaration
LatLng $latLng1,
LatLng $latLng2
) : float
{
}
Description
Computes the distance between two LatLng points.
Parameters
The first LatLng point.
The second LatLng point.
Return
The distance in yards.
Declaration
LatLng[] $latLngsArray
) : float
{
}
Description
Computes the total length of a series of LatLng points.
Parameters
An array of LatLng points.
Return
The total length in yards.
Declaration
LatLng[] $latLngsArray
) : float
{
}
Description
Computes the area of a polygon defined by a series of LatLng points.
Parameters
An array of LatLng points defining the polygon.
Return
The area in square meters.
Declaration
LatLng[] $latLngsArray,
bool $signed = true
) : float
{
}
Description
Computes the signed area of a polygon defined by a series of LatLng points.
Parameters
An array of LatLng points defining the polygon.
Whether to return a signed area.
Return
The signed area in square meters.
Declaration
float $lat
) : float
{
}
Description
Clamps a latitude value to be within valid bounds.
Parameters
The latitude to clamp.
Return
The clamped latitude value.
Declaration
float $lng
) : float
{
}
Description
Wraps a longitude value to be within valid bounds.
Parameters
The longitude to wrap.
Return
The wrapped longitude value.
Declaration
LatLng $latLng1,
LatLng $latLng2
) : float
{
}
Description
Computes the great circle distance (in radians) between two points. Uses the Haversine formula.
Parameters
The first LatLng point.
The second LatLng point.
Return
The distance in radians.
Declaration
LatLng $latLng1,
LatLng $latLng2,
LatLng $latLng3,
bool $signed
) : float
{
}
Description
Computes the spherical excess using L'Huilier's Theorem.
Parameters
The first vertex of the triangle.
The second vertex of the triangle.
The third vertex of the triangle.
Whether to return a signed value.
Return
The spherical excess.
MagicObject\Geometry\Triangle
Declaration
Package
MagicObject\GeometryAuthors
- Kamshory
Links
Description
Class representing a triangle defined by three Point objects.
This class represents a triangle in a 2D space using three vertices. It provides methods to calculate the lengths of the sides and the area using Heron's formula.
Properties
Declaration
Description
Vertex A of the triangle.
Declaration
Description
Vertex B of the triangle.
Declaration
Description
Vertex C of the triangle.
Declaration
Description
Length of side opposite to vertex A.
Declaration
Description
Length of side opposite to vertex B.
Declaration
Description
Length of side opposite to vertex C.
Methods
Declaration
Point $a,
Point $b,
Point $c
)
{
}
Description
Constructor to initialize the Triangle with three Point objects.
Parameters
The first vertex of the triangle.
The second vertex of the triangle.
The third vertex of the triangle.
Declaration
{
}
Description
Calculate the area of the triangle using Heron's formula.
Return
The area of the triangle.
MagicObject\Language\PicoEntityLanguage
Declaration
Package
MagicObject\LanguageAuthors
- Kamshory
Links
Description
Entity Language Class
This class manages entity language configurations, including loading labels and handling different language options.
Constants
Properties
Declaration
Description
Current language code.
Declaration
Description
Array of PicoLanguage objects.
Declaration
Description
Table identity object.
Declaration
Description
Labels for the entity.
Declaration
Description
Entity class name.
Declaration
Description
Entity language code.
Methods
Declaration
MagicObject|null $entity = null
)
{
}
Description
Constructor
Parameters
The entity to load.
Declaration
MagicObject $entity
) : self
{
}
Description
Load data into the object from the given entity.
Parameters
The entity to load.
Return
Returns the current instance for method chaining.
Declaration
string $code,
object|stdClass|array $reference,
bool $use = false
) : self
{
}
Description
Add a language to the entity.
Parameters
Language code.
Reference data for the language.
Flag to indicate whether to use this language immediately.
Return
Returns the current instance for method chaining.
Declaration
string $code
) : self
{
}
Description
Remove a language from the entity.
Parameters
Language code to remove.
Return
Returns the current instance for method chaining.
Declaration
string $code
) : self
{
}
Description
Set the current language.
Parameters
Language code to set as current.
Return
Returns the current instance for method chaining.
Declaration
bool $asArrayProps = false
) : array
{
}
Description
Get the list of properties of the entity.
Parameters
Flag to determine if result should be returned as an array.
Return
List of properties.
Declaration
PicoAnnotationParser $reflexProp,
PicoGenericObject $parameters,
string $annotation,
string $attribute
) : mixed|null
{
}
Description
Get the content of a specific annotation.
Parameters
Property reflection object.
Parameters associated with the property.
Annotation name to search for.
Attribute name to retrieve.
Return
Declaration
PicoAnnotationParser $reflexProp,
PicoGenericObject $parameters,
string $defaultLabel
) : string
{
}
Description
Define the label for a property.
Parameters
Property reflection object.
Parameters associated with the property.
Default label to use if no annotation is found.
Return
The defined label.
Declaration
string $propertyName,
mixed|null $propertyValue
) : self
{
}
Description
Set a property value.
Parameters
Name of the property to set.
Value to set for the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get a property value.
Parameters
Name of the property to get.
Return
The value of the property or null if not set.
Declaration
string $name
) : mixed
{
}
Description
Magic method to get property values.
Example:
<?php
echo $instance->foo;
Parameters
Name of the property to get.
Return
Value of the property if set, otherwise null.
Declaration
string $name
) : bool
{
}
Description
Check if a property is set or not.
Parameters
Name of the property to check.
Return
True if the property is set, false otherwise.
Declaration
string $method,
array $args
) : mixed|null
{
}
Description
Magic method to handle undefined methods.
This method allows for the dynamic handling of method calls that are not explicitly defined in the class. Specifically, it processes calls to getter methods that start with the prefix "get".
When a method starting with "get" is invoked, this method extracts the property name
from the method name and calls the get method to retrieve the corresponding value.
Supported dynamic getter methods:
-
get<PropertyName>: This will call thegetmethod with the property name derived from the method call. For example, calling$obj->getAge()would result in a call to$this->get('age').If the method name does not start with "get" or does not correspond to a valid property, this method will return
null.
Parameters
Name of the method being called, expected to start with "get".
Arguments passed to the method; typically unused in this context.
Return
The value of the requested property if it exists; otherwise, null.
Declaration
{
}
Description
Get the table identity.
Return
The table identity object.
Declaration
{
}
Description
Get the entity language code.
Return
The entity language code.
Declaration
{
}
Description
Get the entity class name.
Return
The entity class name.
Declaration
{
}
Description
Converts the object to its string representation.
This method checks if the label language and current language are set. If they are, it returns the JSON-encoded string of the label corresponding to the current language. If not, it returns an empty JSON object.
Return
A JSON-encoded string of the label for the current language,
Declaration
{
}
Description
Get the value of defaultLabel
Return
Get default label of the entity
MagicObject\Language\PicoLanguage
Declaration
Package
MagicObject\LanguageAuthors
- Kamshory
Links
Description
Language Class
This class represents a language object, allowing for dynamic property management and loading data from arrays or objects.
Methods
Declaration
stdClass|array|null $data = null
)
{
}
Description
Constructor
Parameters
Optional data to initialize the object.
Declaration
stdClass|array $data
) : self
{
}
Description
Load data into the object.
Parameters
Data to be loaded into the object.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed|null $propertyValue
) : self
{
}
Description
Set a property value.
Parameters
Name of the property to set.
Value to assign to the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get a property value.
Parameters
Name of the property to retrieve.
Return
The value of the property or null if not set.
Declaration
string $name,
mixed $value
) : void
{
}
Description
Magic method to set property values.
Example:
<?php
$instance->foo = 'bar';
Parameters
Name of the property to set.
Value to assign to the property.
Return
Declaration
string $name
) : mixed
{
}
Description
Magic method to get property values.
Example:
<?php
echo $instance->foo;
Parameters
Name of the property to get.
Return
The value stored in the property.
Declaration
string $name
) : bool
{
}
Description
Check if a property is set.
Parameters
Name of the property to check.
Return
True if the property is set, false otherwise.
Declaration
string $name
) : void
{
}
Description
Unset a property value.
Parameters
Name of the property to unset.
Return
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method called when an undefined method is invoked.
This method provides dynamic handling for method calls that are not explicitly defined in the class. It specifically supports two types of method calls:
-
Getter Methods:
- When a method name starts with "get", it retrieves the corresponding property value.
- For example, calling
$obj->getAge()will invoke this method and call$this->get('age').
-
Equality Check Methods:
- When a method name starts with "equals", it checks if the provided parameter is equal to the corresponding property value.
- For example, calling
$obj->equalsAge($someValue)will check if$someValueis equal to the value of theageproperty.
If the method does not start with "get" or "equals", this method will return null.
Parameters
Name of the method being called. It should start with "get" or "equals".
Parameters passed to the method; for equality checks, it typically contains the value to compare.
Return
The return value of the getter method or the result of the equality check (true or false), or null if the method is not recognized.
MagicObject\Language\PicoMultilanguage
Declaration
Package
MagicObject\LanguageAuthors
- Kamshory
Links
Description
PicoMultilanguage Class
This class is designed to handle multi-language support within the application, providing functionalities for managing different language translations.
Methods
Declaration
{
}
Description
Constructor
Initialize the multilanguage support with default settings or data.
Declaration
array $languages
) : self
{
}
Description
Load languages
Parameters
An array of language codes and their corresponding translations.
Return
Returns the current instance for method chaining.
Declaration
string $key,
string $language
) : string|null
{
}
Description
Get translation
Parameters
The key for the translation to retrieve.
The language code to retrieve the translation for.
Return
The translation string or null if not found.
MagicObject\Pagination\PicoPagination
Declaration
Package
MagicObject\PaginationAuthors
- Kamshory
Links
Description
Class for handling pagination functionality.
Properties
Declaration
Description
Current page number.
Declaration
Description
Number of items per page.
Declaration
Description
Offset for the current page.
Declaration
Description
Column name to order by.
Declaration
Description
Type of order (ASC or DESC).
Methods
Declaration
int $pageSize = 20,
string $orderby = 'orderby',
string $ordertype = 'ordertype'
)
{
}
Description
Constructor for initializing pagination parameters.
Parameters
Number of items per page (default is 20).
Name of the parameter used to retrieve the ordering value (default is 'orderby').
Name of the parameter used to retrieve the order type (ASC or DESC, default is 'ordertype').
Declaration
string $parameterName = 'page'
) : int
{
}
Description
Parse the current page from the request parameters.
Parameters
Name of the parameter used for the page (default is 'page').
Return
Current page number, at least 1.
Declaration
array|null $map = null,
array|null $filter = null,
string|null $defaultOrderBy = null
) : string
{
}
Description
Create an ORDER BY clause based on the provided parameters.
Parameters
Mapping of order by columns
Filter for order by
Default column name to order by
Return
The generated ORDER BY clause
Throws
if order by is null
Declaration
array|null $filter = null,
string|null $defaultOrderBy = null
) : string|null
{
}
Description
Get the order by column name.
Parameters
Filter for order by
Default column name to order by
Return
The order by column name
Declaration
string|null $defaultOrderType = null
) : string|null
{
}
Description
Get the order type.
Parameters
Default order type (ASC or DESC)
Return
The order type
Declaration
{
}
Description
Get the current page number.
Return
The current page number
Declaration
{
}
Description
Get the page size.
Return
The number of items per page
Declaration
{
}
Description
Get the offset for the current page.
Return
The offset for pagination
Declaration
int $page,
string $parameterName = 'page',
string|null $path = null
) : string
{
}
Description
Generate a URL for a specific page.
Parameters
The page number to generate the URL for
The name of the parameter for the page number
The base path for the URL
Return
The generated URL
MagicObject\Request\InputCookie
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling input from cookies. This class provides functionality to retrieve and parse data from the global $_COOKIE array. It supports options for recursively converting objects and parsing specific types like null and boolean values.
Properties
Declaration
Description
Indicates whether to recursively convert all objects.
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Get the global $_COOKIE variable.
This method is a static wrapper to return the raw cookie data from the $_COOKIE superglobal.
Return
The cookie data from the $_COOKIE superglobal.
MagicObject\Request\InputEnv
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling input from environment variables.
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
MagicObject\Request\InputGet
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling input from HTTP GET requests.
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Get the global variable $_GET.
Return
The data from the $_GET superglobal.
MagicObject\Request\InputPost
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling input from HTTP POST requests.
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Get the global variable $_POST.
Return
The data from the $_POST superglobal.
MagicObject\Request\InputRequest
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling input from HTTP requests.
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
MagicObject\Request\InputServer
Declaration
Package
MagicObject\RequestAuthors
- Kamshory
Links
Description
Class for handling server input data.
This class provides methods to retrieve various server-related information from the PHP $_SERVER superglobal array, such as request method, server address, and script name.
Available methods:
getPhpSelf()returns$_SERVER['PHP_SELF']getGatewayInterface()returns$_SERVER['GATEWAY_INTERFACE']getServerAddr()returns$_SERVER['SERVER_ADDR']getScriptName()returns$_SERVER['SCRIPT_NAME']getServerSoftware()returns$_SERVER['SERVER_SOFTWARE']getServerProtocol()returns$_SERVER['SERVER_PROTOCOL']getRequestMethod()returns$_SERVER['REQUEST_METHOD']getRequestTime()returns$_SERVER['REQUEST_TIME']getRequestTimeFloat()returns$_SERVER['REQUEST_TIME_FLOAT']getQueryString()returns$_SERVER['QUERY_STRING']getDocumentRoot()returns$_SERVER['DOCUMENT_ROOT']getHttps()returns$_SERVER['HTTPS']getRemoteAddr()returns$_SERVER['REMOTE_ADDR']getRemotePort()returns$_SERVER['REMOTE_PORT']getRemoteUser()returns$_SERVER['REMOTE_USER']getRedirectRemoteUser()returns$_SERVER['REDIRECT_REMOTE_USER']getScriptFilename()returns$_SERVER['SCRIPT_FILENAME']getServerAdmin()returns$_SERVER['SERVER_ADMIN']getServerPort()returns$_SERVER['SERVER_PORT']getServerSignature()returns$_SERVER['SERVER_SIGNATURE']getPathTranslated()returns$_SERVER['PATH_TRANSLATED']getRequestUri()returns$_SERVER['REQUEST_URI']getPhpAuthDigest()returns$_SERVER['PHP_AUTH_DIGEST']getPhpAuthUser()returns$_SERVER['PHP_AUTH_USER']getPhpAuthPw()returns$_SERVER['PHP_AUTH_PW']getAuthType()returns$_SERVER['AUTH_TYPE']getPathInfo()returns$_SERVER['PATH_INFO']getOrigPathInfo()returns$_SERVER['ORIG_PATH_INFO']
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
string $key
) : string|null
{
}
Description
Get a specific request header by key.
Parameters
Header key to retrieve.
Return
Returns the header value or null if not found.
Declaration
string $acceptLanguage
) : array
{
}
Description
Parse the 'Accept-Language' HTTP header.
Parameters
The 'Accept-Language' header value.
Return
An associative array of languages with their quality values.
Declaration
bool $general = false
) : string|null
{
}
Description
Get the user's preferred language.
Parameters
Flag to return the general language (default is false).
Return
Returns the user's preferred language or null if not set.
MagicObject\Request\PicoFilterConstant
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class containing constants for various filter types.
This class defines a set of filter constants that can be used for sanitizing and validating input data. Each constant represents a specific filter operation.
Constants
MagicObject\Request\PicoRequest
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Class for handling HTTP requests.
This class provides methods to manage and retrieve data from various types of HTTP requests (GET, POST, COOKIE, ENV, SERVER).
Constants
Properties
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
{
}
Description
Retrieve the raw request body.
Return
The raw body of the request.
Declaration
{
}
Description
Retrieve all request headers.
Return
An associative array of request headers.
Declaration
string $key,
array|null $allHeaders = null
) : string|null
{
}
Description
Retrieve a specific request header by its key.
Parameters
The key of the header to retrieve.
Optional array of all headers.
Return
The value of the header, or null if not found.
MagicObject\Request\PicoRequestBase
Declaration
Package
MagicObject\DatabaseAuthors
- Kamshory
Links
Description
Base class for handling HTTP requests, including input sanitization, data manipulation, and request type checking (GET, POST, AJAX, etc.).
Constants
Properties
Declaration
Description
Class parameters parsed from annotations.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag to force input data to be scalar only.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
Flag for recursive data processing.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
bool $forceScalar = false
)
{
}
Description
Constructor to initialize the request handler and process class annotations.
Parameters
Indicates whether to accept only scalar values for data input.
Throws
If the annotations are invalid or cannot be parsed.
Declaration
mixed $data,
bool $tolower = false
)
{
}
Description
Load data into the object, transforming keys to camelCase (optional).
Parameters
Data to be loaded (can be an array or object).
Flag indicating whether to convert keys to lowercase before loading.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Set a property value dynamically on the object using camelCase notation.
Parameters
Name of the property to set.
Value to assign to the property.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
array|null $params = null
) : mixed|null
{
}
Description
Get a property value dynamically from the object.
Parameters
Name of the property to retrieve.
Optional parameters for filtering the value.
Return
Declaration
bool $snakeCase = false
) : stdClass
{
}
Description
Get the values of all properties as an object (optionally in snake_case).
Parameters
Flag to convert property names to snake_case.
Return
Declaration
bool $reflectSelf = false,
bool $asArrayProps = false
) : array
{
}
Description
Retrieve a list of properties defined in the class, optionally as an array of property names.
Parameters
Flag to indicate whether to include only properties of the current class (not inherited).
Flag to return properties as an array of names.
Return
Declaration
int $type,
string $variableName,
int $filter = 516,
bool $escapeSQL = false
) : mixed
{
}
Description
Filter input data from global variables (GET, POST, etc.) according to the specified filter type.
Parameters
The type of input (e.g., INPUT_GET, INPUT_POST).
The name of the variable to filter.
The filter type to apply (e.g., FILTER_SANITIZE_EMAIL).
Flag to escape SQL-specific characters.
Return
Declaration
mixed $val,
int $filter = 516,
bool $escapeSQL = false,
bool $nullIfEmpty = false,
bool $requireScalar = false
) : mixed|null
{
}
Description
Filter a value (or nested values) based on the specified filter type and optional flags.
Parameters
The value to be filtered.
The filter type to apply (e.g., FILTER_SANITIZE_URL).
Flag to escape SQL-specific characters.
Flag to return null if the value is empty.
Flag to require scalar values.
Return
Declaration
mixed $val
) : mixed|null
{
}
Description
Returns the first scalar value from an array or null if no scalar value is found.
This method extracts scalar values from arrays and ignores other types.
Parameters
The value to process. Typically an array or mixed type.
Return
The first scalar value found, or null if no scalar value exists.
Declaration
mixed $val,
int $filter = 516,
bool $escapeSQL = false,
bool $nullIfEmpty = false
) : mixed
{
}
Description
Filter a single value based on the specified filter type, applying specific sanitization rules.
Parameters
The value to be filtered.
The filter type to apply (e.g., FILTER_SANITIZE_NUMBER_INT).
Flag to escape SQL-specific characters.
Flag to return null if the value is empty.
Return
Declaration
string $input
) : string
{
}
Description
Add escape slashes to a string to protect against SQL injection or special character issues.
Parameters
The input string to escape.
Return
Declaration
stdClass|MagicObject $cfg,
mixed $input
) : float
{
}
Description
Format and return a numeric value by considering application-specific settings for decimal and thousand separators.
Parameters
Configuration object containing separators.
The input value to format.
Return
Declaration
{
}
Description
Check if the request is a GET request.
Return
True if the request method is GET, false otherwise.
Declaration
{
}
Description
Check if the request is a POST request.
Return
True if the request method is POST, false otherwise.
Declaration
{
}
Description
Check if the request is an AJAX request.
Return
True if the request is an AJAX request, false otherwise.
Declaration
{
}
Description
Retrieve the HTTP method used for the current request.
Return
The HTTP method (e.g., GET, POST).
Declaration
{
}
Description
Retrieve the user agent string from the request headers.
Return
The user agent string.
Declaration
{
}
Description
Retrieve the client's IP address from the request headers.
Return
The client's IP address.
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method to handle dynamic method calls.
This method is invoked when an undefined method is called on the object. It supports various dynamic operations based on method names, allowing for flexible interaction with object properties.
Supported method patterns:
-
Countable Check:
countable<propertyName>(): Checks if the specified property is set and is an array.$instance->countableItems(); // Returns true if $items is an array.
-
Existence Check:
isset<propertyName>(): Checks if the specified property is set.$instance->issetUsername(); // Returns true if $username is set.
-
Boolean Check:
is<propertyName>(): Returns true if the specified property is set and evaluates to true (1 or 'true').$instance->isActive(); // Returns true if $active is true or 1.
-
Getter Method:
get<propertyName>(): Retrieves the value of the specified property using theget()method.$value = $instance->getAge(); // Returns the value of $age.
-
Setter Method:
set<propertyName>($value): Sets the specified property to the provided value.$instance->setUsername('newUsername'); // Sets $username to 'newUsername'.
-
Equality Check:
equals<propertyName>($value): Compares the specified value with the property and returns true if they are equal.$isEqual = $instance->equalsUsername('newUsername'); // Returns true if $username is 'newUsername'.
-
Checkbox Handling:
checkbox<propertyName>($value): Sets the property to the provided value if it is not already set.$instance->checkboxTermsAccepted(true); // Sets $termsAccepted to true if it wasn't already.
-
Filter Application:
filter<propertyName>($filter): Applies a filter to the specified property value if it is set.$instance->filterEmail('sanitize'); // Applies 'sanitize' filter to $email if set.
-
Selected Attribute Creation:
createSelected<propertyName>($value): Returns ' selected="selected"' if the property value matches the provided value.$selected = $instance->createSelectedCountry('US'); // Returns ' selected="selected"' if $country is 'US'.
-
Checked Attribute Creation:
createChecked<propertyName>($value): Returns ' checked="checked"' if the property value matches the provided value.$checked = $instance->createCheckedNewsletter(true); // Returns ' checked="checked"' if $newsletter is true.
-
Unset Method:
unset<propertyName>(): Unsets specified property value.$instance->unsetTags(); // Unsets the property 'tags'.
If the method does not match any of the patterns above, the method will return null.
Parameters
Name of the method being called.
Parameters passed to the method.
Return
The result of the method call, or null if the method is not recognized.
Declaration
string|null $value,
string $filterType
) : string|boolean|null
{
}
Description
Apply a filter to the given value based on the specified filter type.
This method sanitizes the input value according to the filter type.
If the filter type is FILTER_SANITIZE_SPECIAL_CHARS, it converts special characters
to HTML entities. If the filter type is FILTER_SANITIZE_BOOL, it evaluates the
value as a boolean. Otherwise, it returns the value unchanged.
Parameters
The value to be filtered.
The type of filter to apply.
Return
The filtered value, a boolean for FILTER_SANITIZE_BOOL, or null if the value is not set.
Declaration
{
}
Description
Check if the JSON naming strategy is snake case.
Return
True if the naming strategy is snake case, false otherwise.
Declaration
{
}
Description
Check if the JSON naming strategy is set to camel case.
This method returns true if the JSON naming strategy is not snake case, indicating that camel case is used instead.
Return
True if the naming strategy is camel case, false otherwise.
Declaration
{
}
Description
Check if the JSON output should be prettified.
This method determines if the prettification option is enabled in the JSON configuration, indicating whether the output should be formatted for readability.
Return
True if the prettify option is enabled, false otherwise.
Declaration
{
}
Description
Check if the request is empty.
This method checks whether the current request has no values set, indicating that it is considered empty.
Return
True if the request is empty, false otherwise.
Declaration
{
}
Description
Convert the object to a JSON string representation.
This method serializes the object to JSON format, with options for pretty printing based on the configuration. It uses the appropriate naming strategy for properties as specified in the class parameters.
Return
The JSON string representation of the object.
Declaration
array $input
) : array
{
}
Description
Forces conversion of string "true"/"false"/"null" to actual boolean/null values in the provided array.
This method uses the convertBooleanAndNull function to modify the input array by converting
string representations of boolean and null values to their actual boolean and null equivalents.
After conversion, it returns the modified array.
Parameters
The input array that will be modified in-place. This array can have nested
Return
The modified input array with the "true", "false", and "null" strings converted
Declaration
array
) : void
{
}
Description
Recursively converts string "true"/"false"/"null" to actual boolean/null values in the given array.
This function processes each element in the array, and if the value is a string representing "true", "false", or "null", it will convert these strings to their corresponding boolean or null values. If a nested array is encountered, the function will call itself recursively to process the nested array.
Parameters
The array to be modified. It is passed by reference, so the original array
Return
This function does not return any value; it modifies the array in place.
MagicObject\Response\Generated\JSONSelectOption
Declaration
Package
MagicObject\Response\GeneratedAuthors
- Kamshory
Links
Description
Class JSONSelectOption
This class fetches data from a database and prepares it for use in JSON select options.
Properties
Declaration
Description
@var array
Methods
Declaration
PicoDatabase $database,
PicoDatabaseQueryBuilder $query,
mixed $defaultValue
)
{
}
Description
Constructor
Initializes the JSONSelectOption with data fetched from the database.
Parameters
Database connection
Query builder for fetching data
Default value to mark as selected
Declaration
array|null $rows,
mixed $defaultValue
)
{
}
Description
Update data with selected value.
Marks the row with the specified default value as selected.
Parameters
Fetched rows from the database
Default value to mark as selected
Declaration
{
}
Description
Get the value of data
Return
Data with selection information
Declaration
{
}
Description
Convert the data to JSON format
Return
JSON representation of the data
MagicObject\Response\Generated\PicoSelectOption
Declaration
Package
MagicObject\Response\GeneratedAuthors
- Kamshory
Links
Description
Class PicoSelectOption
This class generates HTML <option> elements based on data from a MagicObject entity.
Properties
Declaration
Description
Entity object
Declaration
Description
Mapping of value and label fields
Declaration
Description
Selected value
Declaration
Description
Additional attributes for options
Declaration
Description
Rows for generating options
Declaration
Description
Sortable options
Methods
Declaration
MagicObject $object,
array $map,
mixed $value,
array|null $attributes = null,
PicoSortable|null $sortable = null
)
{
}
Description
Constructor
Initializes the PicoSelectOption with the provided parameters and fetches active options.
Parameters
Entity to fetch data from
Mapping for value and label keys
Selected value
Additional attributes for the options
Sortable options for fetching
Declaration
MagicObject $row,
string $attr,
string $value
) : array
{
}
Description
Create attributes for an option element.
Parameters
Entity representing a row.
Attribute name for the option.
Option value.
Return
Attributes for the option element.
Declaration
{
}
Description
Find all active options from the database
Return
Declaration
array $array
) : string
{
}
Description
Convert an array of attributes to an HTML attributes string.
Parameters
Attributes to convert.
Return
String representation of HTML attributes.
Declaration
{
}
Description
Convert the options to HTML <option> elements.
Return
HTML string of <option> elements.
MagicObject\Response\PicoResponse
Declaration
Package
MagicObject\ResponseAuthors
- Kamshory
Links
Description
Class PicoResponse Handles sending HTTP responses with various content types and status codes.
Constants
Methods
Declaration
mixed $data,
bool $prettify = false,
array|null $headers = null,
int $httpStatusCode = 200
) : void
{
}
Description
Send a JSON response to the client.
Parameters
Data to send to the client
Flag to prettify JSON
Response headers
HTTP status code (default: 200)
Return
Declaration
string|null $body,
string|null $contentType = null,
array|null $headers = null,
int $httpStatusCode = 200,
bool $async = false
) : void
{
}
Description
Send the response headers and body to the client.
Parameters
Response body
Content type
Response headers
HTTP status code (default: 200)
Send response asynchronously
Return
Declaration
stdClass|object|array|string|null $body,
array|null $headers = null,
int $httpStatusCode = 200,
bool $async = false
) : void
{
}
Description
Send response as JSON to the client.
Parameters
Response body
Response headers
HTTP status code (default: 200)
Send response asynchronously
Return
Declaration
array $headers
) : void
{
}
Description
Send response headers to the client.
Parameters
Response headers
Return
Declaration
string|null $body,
bool $async = false
) : void
{
}
Description
Send response body to the client.
Parameters
Response body
Send response asynchronously
Return
Declaration
string|null $contentType
) : string
{
}
Description
Get default content type based on the provided content type.
Parameters
Content type
Return
Fixed content type
Declaration
array|null $headers,
string|null $contentType,
int $contentLength = 0
) : array
{
}
Description
Get default response headers.
Parameters
Response headers
Content type
Content length
Return
Fixed response headers
Declaration
int $code = 0,
string|null $text = null
) : int
{
}
Description
Send HTTP status code.
Parameters
HTTP status code
HTTP status text
Return
The HTTP status code sent
Declaration
int $code
) : string|null
{
}
Description
Get HTTP response code text.
Parameters
HTTP status code
Return
The HTTP status text or null if not found
Declaration
{
}
Description
Redirect the browser to the current URL. WARNING: Use this only if there is a POST input that will control the process to prevent an endless loop that could damage the server.
Return
MagicObject\Secret\PicoSecret
Declaration
Package
MagicObject\SecretAuthors
- Kamshory
Links
Description
Default secret key WARNING: Use your own key instead of using default key
Constants
MagicObject\Session\PicoSession
Declaration
Package
MagicObject\SessionAuthors
- Kamshory
Links
Description
Class PicoSession This class manages session handling, providing methods to configure and manipulate sessions.
The class provides an interface for session management, including handling session creation, destruction, configuration, and the ability to store/retrieve session data.
Constants
Properties
Declaration
Description
The state of the session.
The property name starts with an underscore to prevent child classes from overriding its value.
Declaration
Description
The instance of the object.
The property name starts with an underscore to prevent child classes from overriding its value.
Methods
Declaration
SecretObject|null $sessConf = null
)
{
}
Description
Constructor to initialize session configuration.
This constructor accepts a session configuration object and applies settings such as session name, max lifetime, and save handler (Redis or file system).
Parameters
Configuration for the session.
Declaration
string|null $name = null,
int $maxLifeTime = 0
) : self
{
}
Description
Returns the instance of PicoSession. The session is automatically initialized if it wasn't already.
This method ensures that only one instance of PicoSession is created (Singleton pattern).
Parameters
Session name.
Maximum lifetime of the session.
Return
The instance of PicoSession.
Declaration
{
}
Description
(Re)starts the session.
This method starts a session if it hasn't been started already.
Return
True if the session has been initialized, false otherwise.
Declaration
{
}
Description
Checks if the session has been started.
This method checks whether the current session has been started.
Return
True if the session has started, false otherwise.
Declaration
string $name,
mixed $value
) : void
{
}
Description
Stores data in the session.
Example:
<?php
$sessions->foo = 'bar';
This magic method stores data in the PHP session.
Parameters
Name of the data.
The data to store.
Return
Declaration
string $name
) : mixed
{
}
Description
Retrieves data from the session.
Example:
<?php
echo $sessions->foo;
This magic method retrieves data from the PHP session.
Parameters
Name of the data to retrieve.
Return
The data stored in session, or null if not set.
Declaration
string $name
) : bool
{
}
Description
Checks if a value is set in the session.
This magic method checks whether a value is set in the session.
Parameters
Name of the data to check.
Return
True if the data is set, false otherwise.
Declaration
string $name
) : void
{
}
Description
Unsets a value in the session.
This magic method unsets data in the session.
Parameters
Name of the data to unset.
Return
Declaration
{
}
Description
Destroys the current session.
This method destroys the session and clears all session data.
Return
true if the session has been deleted, else false.
Declaration
int $maxlifetime,
string $path,
string $domain,
bool $secure,
bool $httponly,
string $samesite = 'Strict'
) : self
{
}
Description
Sets the session cookie parameters, including lifetime, path, domain, security attributes, and SameSite settings.
This method configures the session cookie parameters such as maximum lifetime, path, domain, and security settings like whether the cookie should be accessible only over HTTPS or only via HTTP. It also sets the SameSite attribute for compatibility with different browsers and PHP versions.
Parameters
Maximum lifetime of the session cookie in seconds.
The path where the cookie will be available on the server.
The domain to which the cookie is available.
Indicates if the cookie should only be transmitted over a secure HTTPS connection.
Indicates if the cookie should be accessible only through the HTTP protocol.
The SameSite attribute of the cookie (Lax, Strict, None). Default is 'Strict'.
Return
Returns the current instance for method chaining.
Declaration
string $name,
string $value,
int $expire,
string $path,
string $domain,
bool $secure,
bool $httponly,
string $samesite = 'Strict'
) : self
{
}
Description
Sets a cookie with the SameSite attribute, supporting both older and newer PHP versions.
This method sets a cookie with a specified SameSite attribute, ensuring compatibility with both PHP versions prior to and after PHP 7.3. It supports cookies with the 'Lax', 'Strict', or 'None' SameSite attributes.
Parameters
The name of the cookie.
The value of the cookie.
The expiration time of the cookie as a Unix timestamp.
The path on the server where the cookie is available.
The domain to which the cookie is available.
Indicates if the cookie should only be transmitted over a secure HTTPS connection.
Indicates if the cookie is accessible only through the HTTP protocol.
The SameSite attribute of the cookie (Lax, Strict, None). Default is 'Strict'.
Return
Returns the current instance for method chaining.
Declaration
string $name
) : self
{
}
Description
Sets the session name.
This method sets the session name for the current session.
Parameters
The name of the session.
Return
Returns the current instance for method chaining.
Declaration
string $path
) : string|false
{
}
Description
Sets the session save path.
This method sets the path where session files will be stored.
Parameters
The session save path.
Return
The session save path on success, false on failure.
Declaration
int $lifeTime
) : self
{
}
Description
Sets the maximum lifetime for the session.
This method sets the maximum lifetime of the session, affecting both garbage collection and cookie expiration.
Parameters
Maximum lifetime for the session in seconds.
Return
Returns the current instance for method chaining.
Declaration
string $host,
int $port,
string $auth
) : self
{
}
Description
Saves the session to Redis.
This method configures the session to be stored in Redis.
Parameters
Redis host.
Redis port.
Redis authentication.
Return
Returns the current instance for method chaining.
Declaration
string $path
) : self
{
}
Description
Saves the session to files.
This method configures the session to be stored in files.
Parameters
The directory where session files will be stored.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Retrieves the current session ID.
This method retrieves the current session ID, if any.
Return
The current session ID.
Declaration
string $id
) : self
{
}
Description
Sets a new session ID.
This method sets a new session ID for the current session.
Parameters
The new session ID.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Converts the session data to a string representation.
This method returns the session data as a JSON-encoded string, which can be useful for debugging
or logging the contents of the session. It encodes the global $_SESSION array into a JSON string.
Return
The JSON-encoded string representation of the session data.
MagicObject\Util\AttrUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class AttrUtil
A utility class for generating HTML attribute strings based
on comparisons between two parameters. This is useful for
dynamically setting attributes like selected and checked
in HTML forms.
This class is intended to be used statically and cannot be instantiated.
Methods
Declaration
mixed $param1,
mixed $param2
) : string
{
}
Description
Returns ' selected="selected"' if $param1 equals $param2.
This method is useful for setting the selected attribute
on option elements in a dropdown when the current value
matches the value of the option.
Example:
<?php
echo AttrUtil::selected($currentValue, $optionValue);
// Outputs: selected="selected" if they match
Parameters
The first parameter to compare.
The second parameter to compare.
Return
The attribute string if matched, empty string otherwise.
Declaration
mixed $param1,
mixed $param2
) : string
{
}
Description
Returns ' checked="checked"' if $param1 equals $param2.
This method is useful for setting the checked attribute
on checkbox or radio button elements when the current value
matches the value of the input.
Example:
<?php
echo AttrUtil::checked($currentValue, $inputValue);
// Outputs: checked="checked" if they match
Parameters
The first parameter to compare.
The second parameter to compare.
Return
The attribute string if matched, empty string otherwise.
MagicObject\Util\ClassUtil\ExtendedReflectionClass
Declaration
Package
MagicObject\Util\ClassUtilDescription
The MIT License (MIT)
Copyright (c) Ozgur (Ozzy) Giritli ozgur@zeronights.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Properties
Declaration
Description
Array of use statements for the class.
Declaration
Description
Flag indicating whether use statements have been parsed.
Methods
Declaration
{
}
Description
Parses the class file and retrieves use statements from the current namespace.
This method reads the source of the class file, tokenizes it, and extracts the use statements. If the use statements have already been parsed, it returns the cached results.
Return
An array of use statements.
Throws
If the class is not user-defined.
Declaration
{
}
Description
Reads the source code of the class file up to the line where the class is defined.
Return
The source code of the class file up to the class definition.
Declaration
string $source
) : array
{
}
Description
Tokenizes the source code and extracts use statements.
This method parses the tokens in the source code to identify use statements and their aliases, returning an array of these statements.
Parameters
The source code to be tokenized.
Return
An array of use statements, including aliases.
Declaration
{
}
Description
Returns the array of use statements for the class.
Return
An array of use statements for the class.
Declaration
string $className
) : string
{
}
Description
Extracts the base name of a class from its fully qualified name.
Parameters
The fully qualified class name.
Return
The base name of the class (i.e., the class name without namespace).
Declaration
string $class
) : bool
{
}
Description
Checks if the class has a specific use statement or alias.
Parameters
The name of the class to check.
Return
True if the class or its alias is found in the use statements, false otherwise.
MagicObject\Util\ClassUtil\PicoAnnotationParser
Declaration
Package
MagicObject\Util\ClassUtilAuthors
- Kamshory
Links
Description
Annotation parser for handling and processing annotations in PHP classes.
This class is designed to read, parse, and manage annotations present in the doc comments of classes, methods, and properties. It provides functionalities to retrieve annotations as arrays or objects, handle key-value pairs from query strings, and validate input parameters.
The PicoAnnotationParser is particularly useful in frameworks or libraries
that rely on annotations for configuration, routing, or metadata purposes.
Constants
Properties
Declaration
Description
Raw docblock
Declaration
Description
Parameters
Declaration
Description
Key pattern
Declaration
Description
End pattern
Declaration
Description
Parsed state
Declaration
Description
Reflection object
Methods
Declaration
mixed
)
{
}
Description
Constructor
Parameters
...$args
Throws
Declaration
{
}
Description
Retrieves all properties of the reflected class or method.
Return
An array of ReflectionProperty objects.
Declaration
string $value
) : bool
{
}
Description
Checks if the given value is null or empty.
Parameters
The value to check.
Return
True if the value is null or empty, otherwise false.
Declaration
string $key
) : array|null
{
}
Description
Parses a single annotation based on the provided key.
Parameters
The annotation key to parse.
Return
The parsed value(s) of the annotation or null if not found.
Declaration
{
}
Description
Parses all annotations found in the raw docblock.
This method should not be called directly; use getParameters() to access
parsed parameters instead.
Return
Declaration
{
}
Description
Fixes duplicated annotations by keeping only the last occurrence.
This method is called during the parsing process.
Return
Declaration
string $name
) : string[]
{
}
Description
Retrieves declared variables from a specified annotation.
Parameters
The name of the annotation to retrieve variables from.
Return
An array of declared variables.
Declaration
mixed $declaration,
string $name
) : string[]
{
}
Description
Parses a variable declaration from an annotation.
Parameters
The raw declaration string.
The name of the annotation for error context.
Return
An array containing 'type' and 'name'.
Throws
if the declaration is not a string or is empty.
Declaration
string $originalValue
) : mixed
{
}
Description
Parse value
Parameters
Original value
Return
Declaration
{
}
Description
Retrieves all parameters from the parsed annotations.
If the annotations have not been parsed yet, this method will trigger parsing.
Return
An associative array of parsed annotation parameters.
Declaration
{
}
Description
Retrieves all parameters as an object of type PicoGenericObject.
If the annotations have not been parsed yet, this method will trigger parsing.
Return
An object containing the parsed annotation parameters.
Declaration
string $key
) : mixed
{
}
Description
Retrieves a specific parameter by its key.
Parameters
The key of the parameter to retrieve.
Return
The value of the specified parameter or null if not found.
Declaration
string $key
) : string|null
{
}
Description
Get the first parameter for a given key from the parsed annotations.
This method retrieves the first value associated with the specified key. If the parameter does not exist or is null, it returns null. If the parameter is an array, it returns the first string element. Otherwise, it returns the value directly.
Parameters
The key for which to retrieve the first parameter.
Return
The first parameter value, or null if not found.
Declaration
array $matches,
array $pair
) : array
{
}
Description
Combine and merge two arrays, where the first array contains keys and the second contains values.
This method checks if both arrays are set and are of the correct type. It combines them into a new associative array and returns the merged result.
Parameters
An array of matched keys and values.
An associative array to merge with.
Return
The merged array containing keys and values from both input arrays.
Declaration
string $parametersString
) : string[]
{
}
Description
Parse key-value pairs from parameters string.
This method extracts key-value pairs from parameters string, which may contain attributes with or without quotes. Numeric attributes will have an underscore prefix. Throws an exception if the input is invalid.
Parameters
The parameters string to parse.
Return
An associative array of parsed key-value pairs.
Throws
If the annotations are invalid or cannot be parsed.
Declaration
array $keys,
string $val
) : bool
{
}
Description
Check if the provided value matches the expected criteria.
This method checks if the given value does not contain an equals sign, quotes, and is not present in the provided keys array.
Parameters
The array of valid keys.
The value to check.
Return
True if the value matches the criteria, otherwise false.
Declaration
string $parametersString
) : PicoGenericObject
{
}
Description
Parse parameters from parameters string and return them as a PicoGenericObject.
This method transforms the key-value pairs parsed from the parameters string into an instance of PicoGenericObject. All numeric attributes will be prefixed with an underscore.
Parameters
The parameters string to parse.
Return
An object containing the parsed key-value pairs.
Throws
If the annotations are invalid or cannot be parsed.
MagicObject\Util\ClassUtil\PicoEmptyParameter
Declaration
Package
MagicObject\Util\ClassUtilDescription
Class PicoEmptyParameter
This class serves as a placeholder for future implementation or to represent an empty parameter in the context of parameter handling within the MagicObject framework. It may be used for type hinting or as a marker in method signatures where no parameters are required.
MagicObject\Util\ClassUtil\PicoObjectParser
Declaration
Package
MagicObject\Util\ClassUtilAuthors
- Kamshory
Links
Description
Class PicoObjectParser
This class provides methods to parse various data formats (YAML, JSON, etc.) into instances of MagicObject. It supports recursive parsing for nested objects and arrays, allowing for flexible data structure handling.
Methods
Declaration
MagicObject $data
) : MagicObject
{
}
Description
Parse a MagicObject from a given data structure.
This method converts a MagicObject instance into a new MagicObject by mapping scalar values and recursively parsing nested objects.
Parameters
The MagicObject instance to parse.
Return
The parsed MagicObject.
Declaration
stdClass|array $data
) : MagicObject
{
}
Description
Parse an object or associative array into a MagicObject.
This method iterates over the given data structure, converting keys to camel case and mapping scalar values directly while handling nested structures recursively.
Parameters
The data to parse, which can be an object or an associative array.
Return
The resulting MagicObject after parsing.
Declaration
array $array
) : bool
{
}
Description
Check if the given array has string keys, indicating it is associative.
Parameters
The array to check.
Return
True if the array has string keys, false otherwise.
Declaration
mixed $data
) : mixed
{
}
Description
Recursively parse data into a MagicObject.
This method handles various data types, converting them into a MagicObject or returning them as-is when appropriate.
Parameters
The data to parse, which may be a MagicObject, array, object, or scalar.
Return
The parsed MagicObject or original data.
Declaration
MagicObject $obj,
string $key,
mixed $val
) : MagicObject
{
}
Description
Update a MagicObject with a key-value pair.
This method determines if the value is an object or array and updates the MagicObject accordingly, using recursion as necessary.
Parameters
The MagicObject to update.
The property name to set.
The property value to assign.
Return
The updated MagicObject.
Declaration
mixed $value
) : bool
{
}
Description
Check if the given value is an object.
Parameters
The value to check.
Return
True if the value is an object, false otherwise.
Declaration
array $data
) : array
{
}
Description
Recursively parse an array into a MagicObject.
This method processes each element of the array, converting nested objects or arrays into MagicObject instances as needed.
Parameters
The array to parse.
Return
An array of parsed MagicObject instances or original values.
Declaration
string $yamlString
) : MagicObject|null
{
}
Description
Parse a YAML string recursively into a MagicObject.
This method converts a YAML string into a structured MagicObject by first parsing the string into an array or object, then processing it.
Parameters
The YAML string to parse.
Return
The resulting MagicObject or null if parsing fails.
Declaration
mixed $data
) : MagicObject|null
{
}
Description
Parse JSON data recursively into a MagicObject.
This method takes JSON-encoded strings or data structures and converts them into MagicObject instances, handling various data types.
Parameters
The JSON data to parse, which can be a string, array, or object.
Return
The resulting MagicObject or null if the data is not valid.
Declaration
string $data
) : mixed
{
}
Description
Parse a string representation of a value into its appropriate type.
This method converts specific string values ('null', 'true', 'false') into their respective PHP types while returning all other strings as-is.
Parameters
The string data to parse.
Return
The parsed value, which may be null, boolean, or string.
MagicObject\Util\ClassUtil\PicoSecretParser
Declaration
Package
MagicObject\Util\ClassUtilAuthors
- Kamshory
Links
Description
Class PicoSecretParser
This class provides methods to parse various data formats (YAML, JSON, etc.) into instances of SecretObject. It supports recursive parsing for nested objects and arrays, allowing for flexible handling of secret-related data structures.
Methods
Declaration
SecretObject $data
) : SecretObject
{
}
Description
Parse a SecretObject from a given data structure.
This method converts a SecretObject instance into a new SecretObject by mapping scalar values and recursively parsing nested objects.
Parameters
The SecretObject instance to parse.
Return
The parsed SecretObject.
Declaration
stdClass|array $data
) : SecretObject
{
}
Description
Parse an object or associative array into a SecretObject.
This method iterates over the given data structure, converting keys to camel case and mapping scalar values directly while handling nested structures recursively.
Parameters
The data to parse, which can be an object or an associative array.
Return
The resulting SecretObject after parsing.
Declaration
array $array
) : bool
{
}
Description
Check if the input is an associative array.
This method determines whether the provided array has string keys, indicating it is associative.
Parameters
The array to check.
Return
True if the array has string keys, false otherwise.
Declaration
mixed $data
) : mixed
{
}
Description
Recursively parse data into a SecretObject.
This method handles various data types, converting them into a SecretObject or returning them as-is when appropriate.
Parameters
The data to parse, which may be a SecretObject, array, object, or scalar.
Return
The parsed SecretObject or original data.
Declaration
SecretObject $obj,
string $key,
mixed $val
) : SecretObject
{
}
Description
Update a SecretObject with a key-value pair.
This method determines if the value is an object or array and updates the SecretObject accordingly, using recursion as necessary.
Parameters
The SecretObject to update.
The property name to set.
The property value to assign.
Return
The updated SecretObject.
Declaration
mixed $value
) : bool
{
}
Description
Check if the given value is an object.
Parameters
The value to check.
Return
True if the value is an object, false otherwise.
Declaration
array $data
) : array
{
}
Description
Recursively parse an array into a SecretObject.
This method processes each element of the array, converting nested objects or arrays into SecretObject instances as needed.
Parameters
The array to parse.
Return
An array of parsed SecretObject instances or original values.
Declaration
string $yamlString
) : SecretObject|null
{
}
Description
Parse a YAML string recursively into a SecretObject.
This method converts a YAML string into a structured SecretObject by first parsing the string into an array or object, then processing it.
Parameters
The YAML string to parse.
Return
The resulting SecretObject or null if parsing fails.
Declaration
string $jsonString
) : SecretObject|null
{
}
Description
Parse JSON data recursively into a SecretObject.
This method takes JSON-encoded strings or data structures and converts them into SecretObject instances, handling various data types.
Parameters
The JSON string to parse.
Return
The resulting SecretObject or null if the data is not valid.
MagicObject\Util\Database\DatabaseTypeConverter
Declaration
Package
MagicObject\Util\DatabaseDescription
Class DatabaseTypeConverter
Provides methods for converting database schema types between MySQL, PostgreSQL, and SQLite. It maps column data types from one database system to another to facilitate schema migration.
Conversion mappings are provided for:
- MySQL to PostgreSQL and SQLite
- PostgreSQL to MySQL and SQLite
-
SQLite to MySQL and PostgreSQL
Use the conversion methods (
mysqlToPostgresql,postgresqlToSQLite, etc.) to convert schema dumps from one format to another.Example:
<?php $converter = new DatabaseTypeConverter(); $postgresqlSchema = $converter->mysqlToPostgresql($mysqlSchema);
Constants
Properties
Declaration
Description
Map of MySQL types to PostgreSQL types.
Declaration
Description
Map of MySQL types to SQLite types.
Declaration
Description
Map of PostgreSQL types to MySQL types.
Declaration
Description
Map of PostgreSQL types to SQLite types.
Declaration
Description
Map of SQLite types to MySQL types.
Declaration
Description
Map of SQLite types to PostgreSQL types.
Methods
Declaration
string $mysqlDump
) : string
{
}
Description
Convert MySQL schema to PostgreSQL schema.
Parameters
MySQL schema dump
Return
PostgreSQL schema
Declaration
string $mysqlDump
) : string
{
}
Description
Convert MySQL schema to SQLite schema.
Parameters
MySQL schema dump
Return
SQLite schema
Declaration
string $postgresqlDump
) : string
{
}
Description
Convert PostgreSQL schema to MySQL schema.
Parameters
PostgreSQL schema dump
Return
MySQL schema
Declaration
string $postgresqlDump
) : string
{
}
Description
Convert PostgreSQL schema to SQLite schema.
Parameters
PostgreSQL schema dump
Return
SQLite schema
Declaration
string $sqliteDump
) : string
{
}
Description
Convert SQLite schema to MySQL schema.
Parameters
SQLite schema dump
Return
MySQL schema
Declaration
string $sqliteDump
) : string
{
}
Description
Convert SQLite schema to PostgreSQL schema.
Parameters
SQLite schema dump
Return
PostgreSQL schema
Declaration
string $dump,
array $typeMap
) : string
{
}
Description
Convert schema based on given type mapping.
Parameters
The schema dump
The type mapping to apply
Return
Converted schema
Declaration
string $createTableLine,
array $lines,
array $typeMap
) : string
{
}
Description
Process CREATE TABLE line and apply type conversions.
Parameters
The CREATE TABLE statement
The schema lines
The type mapping to apply
Return
Converted CREATE TABLE statement
Declaration
string $columnDef,
array $typeMap
) : string
{
}
Description
Process each column and apply type conversion.
Parameters
Column definition line
Type mapping to apply
Return
Converted column definition
Declaration
string $columnType,
string $databaseType
) : string
{
}
Description
Converts a column type from MySQL to the target database type (PostgreSQL or SQLite).
This method takes a column type (e.g., "varchar", "int") and converts it to the appropriate data type for the specified target database (PostgreSQL or SQLite). It uses predefined mappings for MySQL to PostgreSQL and MySQL to SQLite conversions.
Parameters
The column type to be converted (e.g., "varchar", "int").
The target database type. This can be one of the following:
Return
The corresponding column type for the target database, in uppercase.
MagicObject\Util\Database\EntityUtil
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class EntityUtil
A utility class for managing database entities, providing methods to retrieve column names and map entity data to new keys. This class is designed to work with MagicObject instances and can handle various data formats, including arrays and stdClass objects.
Methods
Declaration
MagicObject $entity
) : string[]
{
}
Description
Get the property column names from the entity.
Parameters
The input entity.
Return
An array of property column names.
Declaration
MagicObject $entity
) : string[]
{
}
Description
Get the property join column names from the entity.
Parameters
The input entity.
Return
An array of property join column names.
Declaration
array|stdClass|MagicObject $data,
string[] $map
) : array
{
}
Description
Get entity data mapped to new keys.
Parameters
Data to be mapped.
An array mapping of keys.
Return
An array of mapped data.
Declaration
array $data,
string[] $map
) : array
{
}
Description
Map data from an array.
Parameters
Data to map.
An array mapping of keys.
Return
An array of mapped data.
Declaration
stdClass $data,
string[] $map
) : array
{
}
Description
Map data from a stdClass.
Parameters
Data to map.
An array mapping of keys.
Return
An array of mapped data.
Declaration
MagicObject $data,
string[] $map
) : array
{
}
Description
Map data from a MagicObject.
Parameters
The input entity.
An array mapping of keys.
Return
An array of mapped data.
MagicObject\Util\Database\NativeQueryUtil
Declaration
Description
Utility class for working with SQL queries in the context of MagicObject's database operations.
The NativeQueryUtil class provides methods for handling SQL queries with dynamic parameters,
pagination, and sorting. It includes functionality for generating modified query strings with
array-type parameters, handling return types (e.g., PDOStatement, objects, arrays),
extracting return types and queries from docblocks, and mapping PHP values to PDO parameter types.
Additionally, it supports debugging by logging generated SQL queries.
Key responsibilities include:
- Extracting SQL queries and return types from docblocks.
- Converting PHP types into appropriate PDO parameter types.
- Modifying query strings to handle array parameters and apply pagination/sorting.
- Processing data returned from PDO statements and converting it to the expected return types.
- Debugging SQL queries by sending them to a logger function.
Methods
Declaration
string $databaseType,
string $queryString,
ReflectionParameter[] $callerParams,
array $callerParamValues
) : string
{
}
Description
Replaces array parameters and applies pagination and sorting to the query string.
This method processes the caller's parameters, replacing array-type parameters with string equivalents.
It also adds pagination and sorting clauses if PicoPageable or PicoSortable objects are detected.
Parameters
The database type.
The SQL query string with placeholders.
The parameters of the calling method (reflection objects).
The actual values of the parameters.
Return
The modified query string with array parameters replaced and pagination/sorting applied.
Throws
If parameters are in an unexpected format.
Declaration
PDOStatement $stmt,
string $returnType
) : mixed
{
}
Description
Processes and returns data based on the specified return type.
This method handles various return types like void, PDOStatement, int, object, array,
string, or any specific class name (including array-type hinting).
Parameters
The executed PDO statement.
The return type from the caller's docblock annotation.
Return
The processed return data (e.g., value, object, array, PDOStatement, or JSON string).
Throws
If the return type is invalid or unrecognized.
Declaration
PDOStatement $stmt,
string $returnType
) : array
{
}
Description
Handles return types with array hinting (e.g., MagicObject[], MyClass[]).
Parameters
The executed PDO statement.
The array-type return type (e.g., MagicObject[]).
Return
The processed result as an array of objects.
Throws
If the return type is invalid or unrecognized.
Declaration
PDOStatement $stmt,
string $returnType
) : mixed
{
}
Description
Handles return types that are a single object (e.g., MagicObject, MyClass).
Parameters
The executed PDO statement.
The single-class return type (e.g., MagicObject).
Return
The processed result as a single object.
Throws
If the return type is invalid or unrecognized.
Declaration
PDOStatement $stmt
) : MagicObject[]
{
}
Description
Maps rows from the PDO statement to an array of MagicObject instances.
Parameters
The executed PDO statement.
Return
An array of MagicObject instances.
Declaration
PDOStatement $stmt,
string $className
) : object[]
{
}
Description
Maps rows from the PDO statement to an array of instances of a specified class.
Parameters
The executed PDO statement.
The class name to map rows to.
Return
An array of instances of the specified class.
Throws
If the class does not exist.
Declaration
string $docComment,
string $callerClassName
) : string
{
}
Description
Extracts the return type from the docblock of the caller function.
This method processes the @return annotation, handling self and array types,
and returns the appropriate type, such as the caller class name or void.
Parameters
The docblock of the caller function.
The name of the class where the caller function is defined.
Return
The processed return type (class name, self, or void).
Declaration
string $docComment,
array $callerParamValues
) : string
{
}
Description
Extracts the SQL query string from the docblock or caller's parameters.
This method checks the caller's parameters for a PicoDatabaseQueryTemplate object to extract
the query string. If not found, it looks for the @query annotation in the docblock.
Parameters
The docblock of the caller function.
The parameters passed to the caller.
Return
The extracted SQL query string.
Throws
If no query string is found.
Declaration
array $callerParamValues
) : string
{
}
Description
Extracts the query string from the caller's parameters.
This method looks for a PicoDatabaseQueryTemplate object in the caller's parameters
and returns the query string representation of that object.
Parameters
The parameters passed to the caller function.
Return
The SQL query string or an empty string if no valid object is found.
Declaration
mixed $value
) : stdClass
{
}
Description
Maps a value to the corresponding PDO parameter type.
This method determines the appropriate PDO parameter type based on the given value's type
(e.g., null, boolean, integer, string, DateTime, or PicoSqlJson).
Parameters
The value to determine the PDO parameter type for.
Return
An object with:
Declaration
PicoDatabase $database,
PDOStatement $stmt,
array $params
) : void
{
}
Description
Sends an SQL query to a logger callback for debugging.
This method invokes the callback function defined in the database object, passing the final SQL query generated by combining the statement and parameters.
Parameters
The database instance containing the callback.
The prepared PDO statement.
The parameters bound to the query.
Return
MagicObject\Util\Database\PicoDatabaseUtil
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseUtil
A utility class for handling database operations and specifications within the framework. This class provides methods to retrieve specifications, handle SQL query formatting, and manage data types, ensuring safe and efficient interactions with the database.
Constants
Methods
Declaration
array $params
) : PicoSpecification|null
{
}
Description
Retrieve a PicoSpecification instance from the given parameters.
This method iterates through the provided parameters to find and return the first instance of PicoSpecification. If none is found, null is returned.
Parameters
An array of parameters to search.
Return
Returns the PicoSpecification instance or null if not found.
Declaration
array $params
) : PicoPageable|null
{
}
Description
Retrieve a PicoPageable instance from the given parameters.
This method searches through the parameters for an instance of PicoPageable.
Parameters
An array of parameters to search.
Return
Returns the PicoPageable instance or null if not found.
Declaration
array $params
) : PicoSortable|null
{
}
Description
Retrieve a PicoSortable instance from the given parameters.
This method looks for the first instance of PicoSortable in the parameters.
Parameters
An array of parameters to search.
Return
Returns the PicoSortable instance or null if not found.
Declaration
array $params
) : array
{
}
Description
Retrieve values from the parameters until a PicoPageable instance is found.
This method collects and returns all parameters up to the first PicoPageable instance, effectively filtering the parameters.
Parameters
An array of parameters to process.
Return
An array of values up to the first PicoPageable instance.
Declaration
string $value,
string $type
) : mixed
{
}
Description
Fix a value based on its expected type.
This method normalizes various representations of values (e.g., "true", "false", "null") into their appropriate PHP types based on the expected type.
Parameters
The value to fix.
The expected data type.
Return
The fixed value, converted to the appropriate type.
Declaration
mixed $value,
bool $importFromString
) : bool
{
}
Description
Check if a value is null.
This method checks if the provided value is null or represents "null" as a string.
Parameters
The value to check.
Indicates if the input is from a string.
Return
Returns true if the value is null or the string "null".
Declaration
mixed $value,
bool $importFromString
) : bool
{
}
Description
Check if a value is numeric.
This method checks if the value is a numeric string, specifically when the input is treated as a string.
Parameters
The value to check.
Indicates if the input is from a string.
Return
Returns true if the value is a numeric string and input is from a string.
Declaration
mixed $value,
bool $importFromString = false
) : string
{
}
Description
Escape a value for SQL.
This method prepares a value for safe SQL insertion by escaping it, handling various types including nulls, booleans, strings, and arrays.
Parameters
The value to escape.
Indicates if the input is from a string.
Return
The escaped value suitable for SQL.
Declaration
array $array,
bool $bracket = false,
bool $escape = false
) : string
{
}
Description
Convert an array to a list format for SQL queries.
This method converts an array into a comma-separated string representation, optionally enclosing the result in parentheses.
Parameters
The array to convert.
Indicates if the result should be enclosed in parentheses.
Indicates if the values should be escaped for SQL.
Return
The list representation of the array.
Declaration
string $value
) : string
{
}
Description
Escape a SQL value to prevent SQL injection.
This method escapes special characters in a string to ensure safe SQL execution.
Parameters
The value to escape.
Return
The escaped value.
Declaration
string $where
) : string
{
}
Description
Trim a WHERE clause by removing unnecessary characters.
This method cleans up a raw WHERE clause by trimming whitespace and removing common redundant patterns.
Parameters
The raw WHERE clause to be trimmed.
Return
The cleaned WHERE clause.
Declaration
{
}
Description
Generate a UUID.
Return
A generated UUID.
Declaration
string $line
) : bool
{
}
Description
Filters out empty lines, comments (lines starting with "-- "), and lines that are exactly "--".
This function is commonly used in contexts where a list of lines or strings needs to be processed and filtered by excluding empty lines, comment lines (starting with "-- "), and lines with only the string "--".
Parameters
The line to be checked.
Return
Returns true if the line should be included, false otherwise.
Declaration
string $line
) : string|null
{
}
Description
Determines the delimiter based on the second part of a trimmed line.
This function splits the given line by spaces and checks the second part. If the second part exists,
it returns a semicolon (;) as the delimiter. Otherwise, it returns null.
Parameters
The line to be analyzed, which is trimmed and split by spaces.
Return
Returns ';' if there is a second part after splitting the line, otherwise null.
Declaration
string $sqlText
) : array
{
}
Description
Split a SQL string into separate queries.
This method takes a raw SQL string and splits it into individual queries based on delimiters, handling comments and whitespace.
Parameters
The raw SQL string containing one or more queries.
Return
An array of queries with their respective delimiters.
Declaration
mixed $params
) : bool
{
}
Description
Check if a parameter is an array.
This method checks if the provided parameter is an array.
Parameters
The parameter to check.
Return
Returns true if the parameter is an array, false otherwise.
Declaration
array $params,
string $className
) : object|null
{
}
Description
Find an instance of a specified class in an array of parameters.
This method iterates through the parameters to find an instance of the specified class, returning it if found, or null otherwise.
Parameters
An array of parameters to search.
The name of the class to find.
Return
Returns the instance of the specified class or null if not found.
Declaration
PDOStatement $stmt,
array $params
) : string
{
}
Description
Retrieves the final query to be executed by the PDOStatement.
This function replaces the placeholders in the query with the bound parameter values.
Parameters
The PDOStatement containing the original query.
An array of parameter values to replace the placeholders.
Return
The final query with parameter values substituted.
MagicObject\Util\Database\PicoDatabaseUtilBase
Declaration
Constants
Methods
Declaration
PicoTableInfo $tableInfo
) : array
{
}
Description
Gets the auto-increment keys from the provided table information.
Parameters
Table information.
Return
An array of auto-increment key names.
Declaration
MagicObject $data,
int $maxRecord,
callable|null $callbackFunction
) : bool
{
}
Description
Determines whether fetching data is not required based on the provided parameters.
This method checks if fetching data is not necessary based on the specified conditions:
- The
getFindOption()of the$dataobject must have theFIND_OPTION_NO_FETCH_DATAflag set. - The
$maxRecordmust be greater than 0. - The
$callbackFunctionmust be defined and callable.
Parameters
The data object, typically an instance of MagicObject or similar.
The maximum number of records to fetch.
Optional callback function that should be callable.
Return
Returns true if fetching data is not required, otherwise false.
Declaration
mixed $data
) : bool
{
}
Description
Checks if the given data is an array of MagicObject instances.
This function checks whether the provided data is an array and whether the first element in the array
is an instance of MagicObject. It is used to validate that the data structure is compatible with
operations expecting an array of MagicObject instances.
Parameters
The data to be checked.
Return
Returns true if the data is an array and the first element is a MagicObject instance, otherwise false.
Declaration
mixed $callbackFunction
) : bool
{
}
Description
Checks if the provided callback function is callable.
This method checks whether the $callbackFunction is set and if it is a valid callable function.
It ensures that the provided function can be invoked during the execution of the code.
Parameters
The callback function to be checked.
Return
Returns true if the function is callable, otherwise false.
Declaration
string $picoTableName,
array $columns,
PicoPageData $data,
int $maxRecord,
callable|null $callbackFunction
) : array
{
}
Description
Fetches records from the provided data source and processes them in batches.
This method retrieves records from the specified data source (using a PDO statement) in batches, processes each record by mapping it to the required columns, and buffers the records until the specified maximum number is reached. When the batch size is met, the records are processed using an optional callback function, and the buffer is reset for the next batch.
Parameters
The name of the target table where data will be inserted.
Array of columns to be used for processing each record.
The data source containing records to be fetched, usually an instance of PicoPageData.
The maximum number of records to fetch in a single query (default is 100).
Optional callback function to process the generated SQL
Return
An array of records that are fetched and processed. This will return the remaining
Declaration
array $columns,
string $picoTableName,
MagicObject|PicoPageData|array $data,
int $maxRecord = 100,
callable|null $callbackFunction = null
) : string|null
{
}
Description
Dumps data from various sources into SQL INSERT statements.
This method processes data from PicoPageData, MagicObject, or an array of MagicObject instances and generates SQL INSERT statements. It supports batching of records and allows for a callback function to handle the generated SQL statements.
Parameters
Array of columns for the target table.
Name of the target table.
Data to be dumped. Can be a PicoPageData instance,
Maximum number of records to process in a single query (default is 100).
Optional callback function to process the generated SQL
Return
SQL INSERT statements or null if no data was processed.
Declaration
array $columns,
string $picoTableName,
MagicObject $record
) : string
{
}
Description
Constructs an SQL INSERT statement for a single record.
This method takes a data record and maps it to the corresponding columns of the target table, generating an SQL INSERT statement. It uses the PicoDatabaseQueryBuilder to build the query.
Parameters
Associative array mapping column names to their definitions in the target table.
Name of the target table where the record will be inserted.
The data record to be dumped into the SQL statement.
Return
The generated SQL INSERT statement.
Declaration
SecretObject $tableInfo,
int $maxRecord
) : int
{
}
Description
Retrieves the maximum record limit for a query.
This method checks the specified table information for a maximum record value and ensures that the returned value is at least 1. If the table's maximum record limit is defined, it overrides the provided maximum record.
Parameters
The table information containing maximum record settings.
The maximum record limit per query specified by the user.
Return
The effective maximum record limit to be used in queries.
Declaration
mixed[] $data,
string[] $columns,
string[]|null $maps = null
) : mixed[]
{
}
Description
Processes data mapping according to specified column types and mappings.
This method updates the input data by mapping source fields to target fields based on the provided mappings, then filters and fixes the data types according to the column definitions.
Parameters
The input data to be processed.
An associative array mapping column names to their types.
Optional array of mapping definitions in the format 'target:source'.
Return
The updated data array with fixed types and mappings applied.
Declaration
PicoDatabase $databaseSource,
PicoDatabase $databaseTarget,
string $target
) : string[]
{
}
Description
Creates a mapping template between source and target database tables.
This method generates a mapping array that indicates which columns in the target table do not exist in the source table, providing a template for further processing or data transformation.
Parameters
The source database connection.
The target database connection.
The name of the target table.
Return
An array of mapping strings indicating missing columns in the source.
Declaration
PicoDatabase $databaseSource,
PicoDatabase $databaseTarget,
array $tables,
array $sourceTables,
string $target,
array $existingTables
) : array
{
}
Description
Automatically configures import data settings from one database to another.
This method checks if the target table exists in the existing tables. If it does not, it creates
a new SecretObject for the table, determining whether the table is present in the source
database and configuring the mapping accordingly.
Parameters
The source database connection.
The target database connection.
The current array of table configurations.
List of source table names.
The name of the target table to be configured.
List of existing tables in the target database.
Return
Updated array of table configurations with the new table info added if applicable.
Declaration
PicoDatabase $databaseSource,
PicoDatabase $databaseTarget,
string $tableNameSource,
string $tableNameTarget,
SecretObject $tableInfo,
int $maxRecord,
callable $callbackFunction
) : bool
{
}
Description
Imports data from a source database table to a target database table.
This method fetches records from the specified source table and processes them according to the provided mapping and column information. It uses a callback function to handle the generated SQL insert statements in batches, up to a specified maximum record count.
Parameters
The source database from which to import data.
The target database where data will be inserted.
The name of the source table.
The name of the target table.
Information about the table, including mapping and constraints.
The maximum number of records to process in a single batch.
A callback function to handle the generated SQL statements.
Return
True on success, false on failure.
Declaration
SecretObject $config,
callable $callbackFunction
) : bool
{
}
Description
Imports data from the source database to the target database.
This method connects to the source and target databases, executes any pre-import scripts, transfers data from the source tables to the target tables, and executes any post-import scripts.
Parameters
Configuration object containing database and table details.
Callback function to execute SQL scripts.
Return
Returns true on successful import, false on failure.
Declaration
mixed $value
) : string
{
}
Description
Fixes data for safe use in SQL queries.
This method processes a given value and formats it as a string suitable for SQL. It handles strings, booleans, nulls, and other data types appropriately.
Parameters
The value to be processed.
Return
The formatted string representation of the value.
Declaration
mixed[] $data,
string $name,
mixed $value
) : mixed[]
{
}
Description
Fixes boolean data in the provided array.
This method updates the specified key in the input array to ensure that its value is a boolean. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to a boolean based on the condition that if it equals 1, it is set to true; otherwise, false.
Parameters
The input array containing data.
The key in the array to update.
The value to be processed.
Return
The updated array with the fixed boolean data.
Declaration
mixed[] $data,
string $name,
mixed $value
) : mixed[]
{
}
Description
Fixes integer data in the provided array.
This method updates the specified key in the input array to ensure that its value is an integer. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to an integer.
Parameters
The input array containing data.
The key in the array to update.
The value to be processed.
Return
The updated array with the fixed integer data.
Declaration
mixed[] $data,
string $name,
mixed $value
) : mixed[]
{
}
Description
Fixes float data in the provided array.
This method updates the specified key in the input array to ensure that its value is a float. If the value is null or an empty string, it sets the key to null. Otherwise, it converts the value to a float.
Parameters
The input array containing data.
The key in the array to update.
The value to be processed.
Return
The updated array with the fixed float data.
Declaration
string $tableName,
array $data
) : string
{
}
Description
Creates an SQL INSERT query for multiple records.
This method generates an INSERT statement for a specified table and prepares the values for binding in a batch operation. It supports multiple records and ensures proper formatting of values.
Parameters
Name of the table where data will be inserted.
An array of associative arrays, where each associative array
Return
The generated SQL INSERT statement with placeholders for values.
Declaration
array $columns,
string $picoTableName,
MagicObject $record
) : string
{
}
Description
Dumps a single record into an SQL insert statement.
Parameters
Columns of the target table.
Table name.
Data record.
Return
SQL insert statement.
Declaration
mixed[] $data,
string[] $columns
) : mixed[]
{
}
Description
Fixes imported data based on specified column types.
This method processes the input data array and adjusts the values according to the expected types defined in the columns array. It supports boolean, integer, and float types.
Parameters
The input data to be processed.
An associative array mapping column names to their types.
Return
The updated data array with fixed types.
Declaration
PicoDatabase $database,
string $tableName
) : array
{
}
Description
Retrieves the columns of a specified table from the database.
This method executes a SQL query to show the columns of the given table and returns an associative array where the keys are column names and the values are their respective types.
Parameters
Database connection object.
Name of the table whose columns are to be retrieved.
Return
An associative array mapping column names to their types.
Throws
If the query fails or the table does not exist.
Declaration
string $mysqlQuery
) : string
{
}
Description
Converts a MySQL CREATE TABLE query to a PostgreSQL compatible query.
This function takes a SQL CREATE TABLE statement written for MySQL and transforms it into a format compatible with PostgreSQL. It handles common data types, constraints, and syntax differences between the two databases, such as converting data types, removing unsupported clauses (e.g., AUTO_INCREMENT, ENGINE), and adjusting default values and column types.
Parameters
The MySQL CREATE TABLE query to be converted.
Return
The converted PostgreSQL CREATE TABLE query, with MySQL-specific syntax
Throws
If the input query is not a valid MySQL CREATE TABLE query.
Declaration
string $postgresqlQuery
) : string
{
}
Description
Converts a PostgreSQL CREATE TABLE query to a MySQL compatible query.
This function takes a SQL CREATE TABLE statement written for PostgreSQL and transforms it into a format compatible with MySQL. It handles common data types, constraints, and syntax differences between the two databases. The function adjusts data types, removes PostgreSQL-specific clauses, and makes necessary adjustments for MySQL compatibility.
Parameters
The PostgreSQL CREATE TABLE query to be converted.
Return
The converted MySQL CREATE TABLE query, with PostgreSQL-specific syntax
Throws
If the input query is not a valid PostgreSQL CREATE TABLE query.
Declaration
string $defaultValue
) : bool
{
}
Description
Checks if the given value is a native value (true, false, or null).
This function checks if the provided $defaultValue is a string representing
one of the native values: "true", "false", or "null".
Parameters
The value to check.
Return
True if the value is "true", "false", or "null", false otherwise.
Declaration
string $type
) : bool
{
}
Description
Checks if the given type is a boolean type.
This function checks if the provided $type contains the word "bool",
indicating it is a boolean type (e.g., bool, boolean).
Parameters
The type to check.
Return
True if the type contains "bool", false otherwise.
Declaration
string $type
) : bool
{
}
Description
Checks if the given type is a text-based type.
This function checks if the provided $type contains the word "enum", "varchar",
"char", or "text", indicating it is a text-based type (e.g., enum, varchar, char, text).
Parameters
The type to check.
Return
True if the type contains "enum", "varchar", "char", or "text", false otherwise.
Declaration
string $type
) : bool
{
}
Description
Checks if the given type is an integer type.
This function checks if the provided $type contains the word "int",
indicating it is an integer type (e.g., int, integer).
Parameters
The type to check.
Return
True if the type contains "int", false otherwise.
Declaration
string $type
) : bool
{
}
Description
Checks if the given type is a float type.
This function checks if the provided $type contains any of the words
"decimal", "float", "double", or "real", indicating it is a floating-point type.
Parameters
The type to check.
Return
True if the type contains "decimal", "float", "double", or "real", false otherwise.
Declaration
mixed $value
) : bool
{
}
Description
Checks if the given value is an array.
This function checks if the provided $value is set and is an array.
Parameters
The value to check.
Return
True if the value is an array, false otherwise.
Declaration
array $array
) : bool
{
}
Description
Checks if the provided array is not empty.
This method verifies that the input is an array and contains at least one element.
Parameters
The array to be checked.
Return
True if the array is not empty; otherwise, false.
MagicObject\Util\Database\PicoDatabaseUtilInterface
Declaration
Description
Interface PicoDatabaseUtilInterface
Defines methods for managing database structures and data, including table and column management, data import/export, and database configuration.
Key methods include:
- Retrieving column lists from tables.
- Handling auto-increment keys.
- Generating SQL for creating/dropping tables.
- Configuring columns, fixing defaults, and importing data.
-
Mapping and correcting data types during import.
Implementations must ensure data integrity, validation, and error handling during operations.
Methods
MagicObject\Util\Database\PicoDatabaseUtilMySql
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseUtilMySql
Provides utility methods for MySQL database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.
Key features:
- Retrieve column info from MySQL tables.
- Generate CREATE TABLE statements.
- Convert data to SQL INSERT statements.
- Facilitate data import between databases.
-
Ensure data integrity during imports.
Designed for developers working with MySQL to streamline database management tasks.
Methods
Declaration
PicoDatabase $database,
string $tableName
) : array
{
}
Description
Retrieves a list of columns for a specified table.
Parameters
Database connection.
Table name.
Return
An array of column details.
Declaration
PicoTableInfoExtended $tableInfo,
string $tableName,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string|null $engine = 'InnoDB',
string|null $charset = 'utf8mb4'
) : string
{
}
Description
Dumps the structure of a table as a SQL statement.
This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
Parameters
The information about the table, including column details and primary keys.
The name of the table for which the structure is being generated.
Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).
Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
The storage engine to use for the table (optional, default is null).
The character set to use for the table (optional, default is null).
Return
The SQL statement to create the table, including column definitions and primary keys.
Declaration
array $column,
array $autoIncrementKeys,
array $primaryKeys
) : string
{
}
Description
Creates a column definition for a SQL statement.
This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, primary key status, and auto-increment settings. The resulting definition is formatted for use in a CREATE TABLE statement.
Parameters
An associative array containing details about the column:
An array of column names that should have AUTO_INCREMENT property.
An array of primary key columns, each being an associative array
Return
The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.
Declaration
mixed $defaultValue,
string $type
) : mixed
{
}
Description
Fixes the default value for SQL insertion based on its type.
This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.
Parameters
The default value to fix, which can be a string, boolean, or null.
The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).
Return
The fixed default value formatted appropriately for SQL insertion.
Declaration
SecretObject $config
) : SecretObject
{
}
Description
Automatically configures the import data settings based on the source and target databases.
This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.
Parameters
The configuration object containing database and table information.
Return
The updated configuration object with modified table settings.
Declaration
string $columnType
) : string
{
}
Description
Returns the given column type without modification.
This method simply returns the column type passed as an argument. It is useful when no conversion is needed, and you want to retrieve the column type as-is.
Parameters
The column type to be returned.
Return
The same column type passed as input.
MagicObject\Util\Database\PicoDatabaseUtilPostgreSql
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseUtilPostgreSql
Provides utility methods for PostgreSQL database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. It includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, importing data, and ensuring data integrity during imports.
Key features:
- Retrieve column info from PostgreSQL tables.
- Generate CREATE TABLE statements.
- Convert data to SQL INSERT statements.
- Facilitate data import between databases.
-
Fix data types for integrity during imports.
Designed for developers working with PostgreSQL to manage database tasks efficiently.
Methods
Declaration
PicoDatabase $database,
string $tableName
) : array
{
}
Description
Retrieves a list of columns for a specified table in the database.
This method queries the information schema to obtain details about the columns of the specified table, including their names, data types, nullability, and default values.
Parameters
The database connection instance.
The name of the table to retrieve column information from.
Return
An array of associative arrays containing details about each column,
Throws
If the database connection fails or the query cannot be executed.
Declaration
PicoTableInfoExtended $tableInfo,
string $tableName,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string|null $engine = null,
string|null $charset = null
) : string
{
}
Description
Dumps the structure of a table as a SQL statement.
This method generates a SQL CREATE TABLE statement based on the provided table information,
including options to add or omit specific clauses such as "IF NOT EXISTS" and
"DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
Parameters
The information about the table, including column details and primary keys.
The name of the table for which the structure is being generated.
Whether to include "IF NOT EXISTS" in the CREATE statement (default is false).
Whether to include "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
The storage engine to use for the table (optional, default is null).
The character set to use for the table (optional, default is null).
Return
The SQL statement to create the table, including column definitions and primary keys.
Declaration
array $column
) : string
{
}
Description
Creates a column definition for a SQL statement.
This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, and default value. The resulting definition is formatted for use in a CREATE TABLE statement.
Parameters
An associative array containing details about the column:
Return
The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.
Declaration
array $column,
string $type,
array $autoIncrementKeys
) : string
{
}
Description
Adjusts the SQL data type for auto-increment columns.
This method checks if the given column is designated as an auto-increment key and modifies its SQL type accordingly. If the column is a big integer, it will return "BIGSERIAL"; otherwise, it will return "SERIAL" for standard integer types. If the column is not an auto-increment key, it returns the original type.
Parameters
An associative array containing details about the column,
The original data type of the column.
An array of column names that are designated as
Return
The adjusted SQL data type for the column, suitable for use
Declaration
array $column,
array|null $autoIncrementKeys,
array $primaryKeys
) : string
{
}
Description
Creates a column definition for a PostgreSQL SQL statement.
This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, and whether the column should be auto-incrementing. If the column is specified as auto-increment, it will use PostgreSQL's SERIAL or BIGSERIAL data types, depending on the column type.
Parameters
An associative array containing details about the column:
An optional array of column names that should
An array of primary key columns, each being an associative
Return
The SQL column definition formatted as a string, suitable for inclusion
Declaration
mixed $defaultValue,
string $type
) : mixed
{
}
Description
Fixes the default value for SQL insertion based on its type.
This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.
Parameters
The default value to fix, which can be a string, boolean, or null.
The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).
Return
The fixed default value formatted appropriately for SQL insertion.
Declaration
SecretObject $config
) : SecretObject
{
}
Description
Automatically configures the import data settings based on the source and target databases.
This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.
Parameters
The configuration object containing database and table information.
Return
The updated configuration object with modified table settings.
Declaration
string $columnType
) : string
{
}
Description
Converts the given column type from MySQL format to PostgreSQL format.
This method calls the convertMySqlToPostgreSql function to perform the conversion of
the column type from MySQL to PostgreSQL syntax. The method provides an abstraction layer
for converting column types, ensuring compatibility when migrating between MySQL and PostgreSQL.
Parameters
The MySQL column type to be converted.
Return
The equivalent PostgreSQL column type.
Throws
If the column type is not recognized or unsupported.
MagicObject\Util\Database\PicoDatabaseUtilSqlite
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseUtilSqlite
Provides utility methods for SQLite database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.
Key features:
- Retrieve column info from SQLite tables.
- Generate CREATE TABLE statements.
- Convert data to SQL INSERT statements.
- Facilitate data import between databases.
-
Ensure data integrity during imports.
Designed for developers working with SQLite to streamline database management tasks.
Methods
Declaration
MagicObject $entity,
bool $createIfNotExists = false,
bool $dropIfExists = false
) : string
{
}
Description
Generates a SQL CREATE TABLE query based on the provided class annotations.
This function inspects the given class for its properties and their annotations
to construct a SQL statement that can be used to create a corresponding table in a database.
It extracts the table name from the @Table annotation and processes each property
to determine the column definitions from the @Column annotations.
Parameters
The instance of the class whose properties will be used
If true, the query will include an "IF NOT EXISTS" clause.
Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
Return
The generated SQL CREATE TABLE query.
Throws
If the class does not exist or is not accessible.
Declaration
bool $createIfNotExists
) : string
{
}
Description
Returns "IF NOT EXISTS" if specified, otherwise an empty string.
Parameters
Flag indicating whether to include "IF NOT EXISTS".
Return
The "IF NOT EXISTS" clause if applicable.
Declaration
array $pKeyArr,
array $pKeyArrUsed
) : array
{
}
Description
Filter the primary key array to exclude used primary keys.
Parameters
Array of primary key names.
Array of used primary key names.
Return
Filtered array of primary key names.
Declaration
array $column,
array|null $autoIncrementKeys = null,
int $length = 255,
array $pKeyArrUsed = array ( )
) : array
{
}
Description
Determine the SQL data type based on the given column information and auto-increment keys.
Parameters
The column information, expected to include the column name and type.
The array of auto-increment keys, if any.
The length for VARCHAR types.
The array to store used primary key names.
Return
An array containing the determined SQL data type and the updated primary key array.
Declaration
PicoDatabase $database,
string $tableName
) : array
{
}
Description
Retrieves a list of columns for a specified table in the database.
This method queries the information schema to obtain details about the columns of the specified table, including their names, data types, nullability, default values, and any additional attributes such as primary keys and auto-increment.
Parameters
The database connection instance.
The name of the table to retrieve column information from.
Return
An array of associative arrays containing details about each column,
Throws
If the database connection fails or the query cannot be executed.
Declaration
PicoTableInfoExtended $tableInfo,
string $tableName,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string|null $engine = 'InnoDB',
string|null $charset = 'utf8mb4'
) : string
{
}
Description
Dumps the structure of a table as a SQL statement.
This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
Parameters
The information about the table, including column details and primary keys.
The name of the table for which the structure is being generated.
Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).
Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
The storage engine to use for the table (optional, default is null).
The character set to use for the table (optional, default is null).
Return
The SQL statement to create the table, including column definitions and primary keys.
Declaration
string $type
) : string
{
}
Description
Converts MySQL data types to SQLite-compatible types.
This function maps MySQL data types to their equivalent SQLite types. It supports:
tinyint(1)toBOOLEAN,integertoINTEGER,enum()toNVARCHAR(N)with a length based on the maximum length of the enum values plus 2,varchar(N)toNVARCHAR(N)(orvarchartoNVARCHARwithout a length),float,doubletoREAL,decimaltoNUMERIC,textandlongtexttoTEXT,date,datetime,timestamptoTEXT(as SQLite does not have dedicated date/time types).
Parameters
The MySQL data type to convert (e.g., 'tinyint(1)', 'varchar(255)', 'enum(', 'decimal(10,2)').
Return
The corresponding SQLite data type (e.g., 'BOOLEAN', 'NVARCHAR(255)', 'REAL', 'NUMERIC', 'TEXT').
Declaration
array $column
) : string
{
}
Description
Creates a column definition for a SQL statement (SQLite).
This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, and primary key constraints. The resulting definition is formatted for use in a CREATE TABLE statement, suitable for SQLite.
If the column is specified as a primary key with auto-increment, the column type is set to INTEGER, and the PRIMARY KEY constraint is added with auto-increment behavior (SQLite uses INTEGER PRIMARY KEY AUTOINCREMENT).
Parameters
An associative array containing details about the column:
Return
The SQL column definition formatted as a string, suitable for inclusion
Declaration
mixed $defaultValue,
string $type
) : mixed
{
}
Description
Fixes the default value for SQL insertion based on its type.
This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.
Parameters
The default value to fix, which can be a string, boolean, or null.
The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).
Return
The fixed default value formatted appropriately for SQL insertion.
Declaration
SecretObject $config
) : SecretObject
{
}
Description
Automatically configures the import data settings based on the source and target databases.
This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.
Parameters
The configuration object containing database and table information.
Return
The updated configuration object with modified table settings.
Declaration
PicoDatabase $database,
string $tableName
) : bool
{
}
Description
Check if a table exists in the database.
This method queries the database to determine if a specified table exists by checking the SQLite master table. It throws an exception if the table name is null or empty.
Parameters
The database instance to check.
The name of the table to check.
Return
True if the table exists, false otherwise.
Throws
If the table name is null or empty.
Declaration
string $columnType
) : string
{
}
Description
Converts a MySQL column type to its equivalent SQLite column type.
This method uses the mysqlToSqliteType function to convert a MySQL column type
to the appropriate SQLite column type. It helps facilitate database migration or
compatibility between MySQL and SQLite.
Parameters
The MySQL column type to be converted.
Return
The equivalent SQLite column type.
Throws
If the column type is not recognized or unsupported.
MagicObject\Util\Database\PicoDatabaseUtilSqlServer
Declaration
Package
MagicObject\Util\DatabaseAuthors
- Kamshory
Links
Description
Class PicoDatabaseUtilSqlServer
Provides utility methods for SQL Server database operations, extending PicoDatabaseUtilBase and implementing PicoDatabaseUtilInterface. This class includes functions for retrieving column information, generating CREATE TABLE statements, dumping data to SQL insert statements, facilitating data imports, and ensuring data integrity during the import process.
Key features:
- Retrieve column info from SQL Server tables.
- Generate CREATE TABLE statements.
- Convert data to SQL INSERT statements.
- Facilitate data import between databases.
-
Ensure data integrity during imports.
Designed for developers working with SQL Server to streamline database management tasks.
Constants
Methods
Declaration
PicoDatabase $database,
string $tableName
) : array
{
}
Description
Retrieves a list of columns for a specified table in SQL Server.
This method queries the system views to obtain details about the columns of the specified table, including their names, data types, nullability, default values, and whether they are part of the primary key.
Parameters
The database connection instance.
The name of the table to retrieve column information from.
Return
An array of associative arrays containing details about each column,
Throws
If the database connection fails or the query cannot be executed.
Declaration
PicoTableInfoExtended $tableInfo,
string $tableName,
bool $createIfNotExists = false,
bool $dropIfExists = false,
string|null $engine = 'InnoDB',
string|null $charset = 'utf8mb4'
) : string
{
}
Description
Dumps the structure of a table as a SQL statement for SQL Server.
This method generates a SQL CREATE TABLE statement based on the provided table information, including the option to include or exclude specific clauses such as "IF NOT EXISTS" and "DROP TABLE IF EXISTS". It also handles the definition of primary keys if present.
Parameters
The information about the table, including column details and primary keys.
The name of the table for which the structure is being generated.
Whether to add "IF NOT EXISTS" in the CREATE statement (default is false).
Whether to add "DROP TABLE IF EXISTS" before the CREATE statement (default is false).
The storage engine to use for the table (optional, default is null).
The character set to use for the table (optional, default is null).
Return
The SQL statement to create the table, including column definitions and primary keys.
Declaration
array $column,
array $autoIncrementKeys,
array $primaryKeys
) : string
{
}
Description
Creates a column definition for a SQL statement for SQL Server.
This method constructs a SQL column definition based on the provided column details, including the column name, data type, nullability, default value, primary key status, and auto-increment settings. The resulting definition is formatted for use in a CREATE TABLE statement.
Parameters
An associative array containing details about the column:
An array of column names that should have IDENTITY(1,1) property.
An array of primary key columns, each being an associative array
Return
The SQL column definition formatted as a string, suitable for inclusion in a CREATE TABLE statement.
Declaration
mixed $defaultValue,
string $type
) : mixed
{
}
Description
Fixes the default value for SQL insertion based on its type.
This method processes the given default value according to the specified data type, ensuring that it is correctly formatted for SQL insertion. For string-like types, the value is enclosed in single quotes, while boolean and null values are returned as is.
Parameters
The default value to fix, which can be a string, boolean, or null.
The data type of the column (e.g., ENUM, CHAR, TEXT, INT, FLOAT, DOUBLE).
Return
The fixed default value formatted appropriately for SQL insertion.
Declaration
SecretObject $config
) : SecretObject
{
}
Description
Automatically configures the import data settings based on the source and target databases.
This method connects to the source and target databases, retrieves the list of existing tables, and updates the configuration for each target table by checking its presence in the source database. It handles exceptions and logs any errors encountered during the process.
Parameters
The configuration object containing database and table information.
Return
The updated configuration object with modified table settings.
Declaration
string $columnType
) : string
{
}
Description
Converts the given column type from MySQL format to SQL Server format.
This method performs the conversion of the column type from MySQL to SQL Server syntax. It ensures compatibility when migrating column types from MySQL to SQL Server.
Parameters
The MySQL column type to be converted.
Return
The equivalent SQL Server column type.
Throws
If the column type is not recognized or unsupported.
Declaration
string $mysqlQuery
) : string
{
}
Description
Converts a MySQL CREATE TABLE query to a SQL Server compatible query.
This function takes a SQL CREATE TABLE statement written for MySQL and transforms it into a format compatible with SQL Server. It handles common data types, constraints, and syntax differences between the two databases, such as converting data types, removing unsupported clauses (e.g., AUTO_INCREMENT), and adjusting default values and column types.
Parameters
The MySQL CREATE TABLE query to be converted.
Return
The converted SQL Server CREATE TABLE query, with MySQL-specific syntax
Throws
If the input query is not a valid MySQL CREATE TABLE query.
MagicObject\Util\Database\PicoQueryTranslator
Declaration
Package
MagicObject\Util\DatabaseDescription
Class PicoQueryTranslator
This class is responsible for translating database query structures between different SQL dialects. It takes SQL queries written in one dialect (e.g., MySQL) and converts them into another dialect (e.g., PostgreSQL, SQLite). The class handles differences in syntax, keywords, functions, and other database-specific features.
Key functionalities of this class include:
- Translating data types between different SQL flavors.
- Adjusting query syntax to match the conventions of different database systems.
-
Converting SQL-specific expressions like
AUTO_INCREMENTto equivalent expressions in other databases.This class is typically used when migrating databases or working with systems that need to support multiple database engines.
Properties
Declaration
Description
Array mapping of database field types to SQLite data types.
Declaration
Description
Array mapping of database field types to MySQL data types.
Declaration
Description
Array mapping of database field types to PostgreSQL data types.
Methods
Declaration
string|null $str,
string $search,
string $replacement
) : string|null
{
}
Description
Replaces all occurrences of a substring in the given string.
This function uses a regular expression to replace all matches of the search pattern with the specified replacement.
Parameters
The string to search and replace in. If null, returns null.
The substring to search for.
The substring to replace the search pattern with.
Return
The modified string, or null if the input string is null.
Declaration
string $value,
string $targetType
) : string
{
}
Description
Translates the provided SQL query to a specified target database format.
This method converts the provided SQL string into a format compatible with the specified target database (MySQL, PostgreSQL, or SQLite), ensuring that all relevant data types and structures are adapted.
Parameters
The SQL query to be translated.
The target database type ('mysql', 'pgsql', 'sqlite').
Return
The translated SQL query in the target database format.
Declaration
array $table,
string $targetType
) : string
{
}
Description
Converts a table schema to a query compatible with the specified database type.
This method takes the parsed table schema and converts it to the corresponding SQL syntax for the target database.
Parameters
The table schema to convert.
The target database type ('mysql', 'pgsql', 'sqlite').
Return
The converted table schema in the target database format.
Declaration
array $table,
string $targetType
) : string
{
}
Description
Converts a table schema to SQLite-specific SQL syntax.
This method adapts the provided table schema to SQLite format, including data type conversions and primary key handling.
Parameters
The table schema to convert.
The target database type ('sqlite').
Return
The converted table schema in SQLite format.
Declaration
array $table,
string $targetType
) : string
{
}
Description
Converts a table schema to MySQL-specific SQL syntax.
This method adapts the provided table schema to MySQL format, including data type conversions and primary key handling.
Parameters
The table schema to convert.
The target database type ('mysql').
Return
The converted table schema in MySQL format.
Declaration
array $table,
string $targetType
) : string
{
}
Description
Converts a table schema to PostgreSQL-specific SQL syntax.
This method adapts the provided table schema to PostgreSQL format, including data type conversions and primary key handling.
Parameters
The table schema to convert.
The target database type ('pgsql').
Return
The converted table schema in PostgreSQL format.
Declaration
string $sqliteTable,
string $targetType
) : mixed
{
}
Description
Converts a given table for SQLite target type.
This method uses a common toTable function to convert a table for SQLite.
Parameters
The name of the SQLite table.
The target database type (e.g., 'sqlite').
Return
The result of the toTable method.
Declaration
string $mysqlTable,
string $targetType
) : mixed
{
}
Description
Converts a given table for MySQL target type.
This method uses a common toTable function to convert a table for MySQL.
Parameters
The name of the MySQL table.
The target database type (e.g., 'mysql').
Return
The result of the toTable method.
Declaration
string $pgTable,
string $targetType
) : mixed
{
}
Description
Converts a given table for PostgreSQL target type.
This method uses a common toTable function to convert a table for PostgreSQL.
Parameters
The name of the PostgreSQL table.
The target database type (e.g., 'pgsql').
Return
The result of the toTable method.
Declaration
string $targetType
) : bool
{
}
Description
Checks if the target type is MySQL or MariaDB.
This method verifies if the target type matches MySQL or MariaDB.
Parameters
The target database type.
Return
Returns true if the target type is 'mysql' or 'mariadb', otherwise false.
Declaration
string $targetType
) : bool
{
}
Description
Checks if the target type is PostgreSQL.
This method verifies if the target type matches PostgreSQL or PGSQL.
Parameters
The target database type.
Return
Returns true if the target type is 'pgsql' or 'postgresql', otherwise false.
Declaration
string $targetType
) : bool
{
}
Description
Checks if the target type is SQLite.
This method verifies if the target type matches SQLite.
Parameters
The target database type.
Return
Returns true if the target type is 'sqlite', otherwise false.
Declaration
string $columnType
) : bool
{
}
Description
Checks if the given column type is a real number (e.g., FLOAT, DOUBLE, REAL, DECIMAL).
This method checks if the column type corresponds to a real number type.
Parameters
The column type to check.
Return
Returns true if the column type is a real number, otherwise false.
Declaration
string $columnType
) : bool
{
}
Description
Checks if the given column type is a boolean type (e.g., BOOLEAN, BOOL, TINYINT(1)).
This method checks if the column type corresponds to a boolean type.
Parameters
The column type to check.
Return
Returns true if the column type is boolean, otherwise false.
Declaration
string $type,
int|null $length = null
) : string
{
}
Description
Converts a column type to the SQLite type format.
Parameters
The original column type.
The column length (optional).
Return
The converted SQLite column type.
Declaration
string $type,
int|null $length = null
) : string
{
}
Description
Converts a column type to the MySQL type format.
Parameters
The original column type.
The column length (optional).
Return
The converted MySQL column type.
Declaration
string $type,
int|null $length = null
) : string
{
}
Description
Converts a column type to the PostgreSQL type format.
Parameters
The original column type.
The column length (optional).
Return
The converted PostgreSQL column type.
Declaration
string $inputString
) : array
{
}
Description
Parses an ENUM type value and extracts the values in single quotes, also calculating the maximum length.
Parameters
The ENUM values in a string format.
Return
An associative array containing the result array and maximum length of ENUM values.
Declaration
string $inputString
) : array
{
}
Description
Parses a numeric type value like DECIMAL(6,3), NUMERIC(10,2), etc.
Parameters
The numeric value in string format, like 'DECIMAL(6, 3)'.
Return
An associative array containing the type (e.g., DECIMAL) and the length (total digits) and scale (digits after the decimal point).
Declaration
array $table,
string $targetType
) : string
{
}
Description
Converts the table schema into a SQL CREATE TABLE statement for the specified database.
This method generates a SQL CREATE TABLE statement based on the provided table schema and target database type, adapting column definitions, default values, and other relevant attributes.
Parameters
The table schema to convert.
The target database type ('mysql', 'pgsql', 'sqlite').
Return
The SQL CREATE TABLE statement.
Declaration
string $type,
int $length
) : bool
{
}
Description
Checks if the column type is TINYINT with a length of 1.
This method checks if the given column type is 'TINYINT' and if its length is exactly 1, which is commonly used to represent boolean values in certain databases.
Parameters
The data type of the column (e.g., 'TINYINT').
The length of the column (e.g., 1).
Return
True if the type is 'TINYINT' and length is 1, otherwise false.
Declaration
string $type
) : bool
{
}
Description
Checks if the column type is an integer (e.g., TINYINT, SMALLINT, INT, BIGINT).
Parameters
The column data type (e.g., 'INT', 'BIGINT').
Return
True if the column type is an integer type, otherwise false.
Declaration
bool $autoIncrement,
string $targetType
) : bool
{
}
Description
Determines if a column is auto-incremented for MySQL databases.
Parameters
Whether the column is set to auto-increment.
The target database type (e.g., 'mysql', 'mariadb').
Return
True if the column is auto-incremented in MySQL or MariaDB, otherwise false.
Declaration
string $value
) : bool
{
}
Description
Checks if a value is not empty (not null or an empty string).
Parameters
The value to check.
Return
True if the value is not empty, otherwise false.
Declaration
bool $primaryKey,
string $defaultValue
) : bool
{
}
Description
Determines if a column has a default value, excluding primary keys.
Parameters
Whether the column is a primary key.
The default value of the column.
Return
True if the column has a default value, otherwise false.
Declaration
string $tableName,
string $targetType
) : string
{
}
Description
Fixes the table name according to the target database type.
This method adjusts the table name by removing any database prefix and applying the appropriate syntax for the target database (e.g., quoting for MySQL or PostgreSQL).
Parameters
The name of the table to fix.
The target database type (e.g., 'mysql', 'pgsql').
Return
The fixed table name.
Declaration
string $columnName,
string $targetType
) : string
{
}
Description
Fixes the column name according to the target database type.
This method applies proper quoting for column names based on the target database (e.g., MySQL uses backticks for column names).
Parameters
The name of the column to fix.
The target database type (e.g., 'mysql').
Return
The fixed column name.
Declaration
string $defaultValue,
string $columnType
) : string
{
}
Description
Generates the default value SQL for a column based on its type.
This method returns the appropriate default value syntax for the column's type, handling different types such as BOOLEAN, INTEGER, and REAL.
Parameters
The default value to apply to the column.
The type of the column (e.g., 'BOOLEAN', 'INT').
Return
The default value SQL definition for the column.
Declaration
mixed $value
) : string
{
}
Description
Converts a value to a boolean format.
Parameters
The value to convert.
Return
The converted boolean value ('TRUE' or 'FALSE').
Declaration
mixed $value
) : int
{
}
Description
Converts a value to an integer format.
Parameters
The value to convert.
Return
The converted integer value.
Declaration
mixed $value
) : float
{
}
Description
Converts a value to a real number format.
Parameters
The value to convert.
Return
The converted real number value.
Declaration
string $defaultValue,
string $targetType
) : string
{
}
Description
Fixes default value for SQLite.
Parameters
The default value to fix.
The target database type.
Return
The fixed default value.
Declaration
string $text
) : string
{
}
Description
Escapes special characters in a string for use in SQL statements.
This method wraps the PHP addslashes() function, which adds backslashes before characters
that need to be escaped in SQL, such as quotes, backslashes, and NULL characters.
Parameters
The input string to escape.
Return
The escaped string with special characters properly handled.
Declaration
string $sql,
string $targetType
) : array
{
}
Description
Extracts the DROP TABLE IF EXISTS queries from the provided SQL string.
Parameters
The SQL string to be processed.
The type of database ('pgsql', 'mysql', or 'mariadb') to format the table names accordingly.
Return
An array of objects, each containing the name of a table to be dropped.
Declaration
string $input
) : string
{
}
Description
Extracts the table name from the input string, removing schema if present.
Parameters
The input string (may contain schema.table or just table).
Return
The extracted table name without schema.
MagicObject\Util\Database\PicoSqlParser
Declaration
Package
MagicObject\Util\DatabaseLinks
Description
Class PicoSqlParser
This class parses SQL CREATE TABLE statements to extract table information such as:
- Table name
- Column names
- Data types
- Column attributes (nullable, default value, etc.)
-
Primary keys and other constraints
This class is useful for generating database documentation, creating Entity Relationship Diagrams (ERDs), or analyzing database structures from SQL DDL scripts.
Example usage:
<?php $parser = new PicoSqlParser($sql); $result = $parser->getResult();
Constants
Properties
Declaration
Description
List of valid SQL data types supported by this parser.
Declaration
Description
Information about the parsed tables, including columns, data types, and primary keys.
Methods
Declaration
string|null $sql = null
)
{
}
Description
Constructor to initialize the parser. Optionally parses an SQL statement immediately upon instantiation.
Parameters
The SQL statement to parse (optional).
Declaration
array $haystack,
mixed $needle
) : bool
{
}
Description
Checks if a specific element exists in the array.
Parameters
Array to search in.
Element to search for.
Return
True if the element is found, false otherwise.
Declaration
string $sql
) : array
{
}
Description
Parses a CREATE TABLE statement to extract table information.
Parameters
SQL statement to be parsed.
Return
Information about the table, columns, and primary key.
Throws
if the SQL statement is not a valid CREATE TABLE statement.
Declaration
string $text
) : string|null
{
}
Description
Extracts the length of a data type if it is defined in the SQL (e.g., VARCHAR(100)).
Parameters
The data type definition, e.g., VARCHAR(100).
Return
Returns the length if defined (e.g., 100 for VARCHAR(100)), or null if not.
Declaration
string $dataType
) : bool
{
}
Description
Validates whether the provided data type is in the list of supported types.
Parameters
The data type to check (e.g., int, varchar).
Return
Returns true if the data type is valid, false otherwise.
Declaration
{
}
Description
Returns the result of the most recent table parsing.
Return
The parsed table information (name, columns, primary keys).
Declaration
{
}
Description
Initializes the list of valid SQL data types supported by the parser.
This method sets the list of data types that the parser recognizes, such as varchar, int, timestamp, boolean,
json, uuid, etc. These data types correspond to common column types in various SQL-based databases like PostgreSQL,
MySQL, and SQLite. The list may be used to validate or process SQL statements when parsing or generating SQL.
Return
Declaration
string $sql
) : array
{
}
Description
Parses all CREATE TABLE statements in the provided SQL text.
Parameters
The SQL statements to parse (can contain multiple CREATE TABLE statements).
Return
An array of parsed tables with their columns and primary keys.
Declaration
{
}
Description
Returns the list of valid SQL data types that the parser recognizes.
Return
An array of valid SQL data types.
Declaration
{
}
Description
Retrieves information about all the tables parsed.
Return
An array containing parsed information for all tables.
MagicObject\Util\Database\PicoTableParser
Declaration
Package
MagicObject\Util\DatabaseDescription
The PicoTableParser class is responsible for parsing SQL CREATE TABLE statements to extract table and column information. It validates data types, handles constraints like primary keys and auto-increment fields, and processes table comments and default values. This class can handle multiple SQL statements, parsing them into individual queries, and extracting structured information about the database schema from SQL scripts.
The class supports parsing complex SQL table definitions, including field types, constraints (e.g., primary keys, auto-increments), and special data types (e.g., ENUM, SET, JSON). Additionally, it provides methods to normalize and format SQL defaults, handle multi-line SQL statements, and retrieve detailed schema information for each parsed table.
Example usage: $parser = new PicoTableParser($sql); $tableInfo = $parser->getResult();
The returned result contains structured information about each table, including columns, their types, constraints, and additional attributes.
Properties
Declaration
Description
List of valid SQL data types used for column validation.
Declaration
Description
Holds information about the parsed tables, including columns and their properties.
Methods
Declaration
string|null $sql = null
)
{
}
Description
PicoTableParser constructor.
Initializes the PicoTableParser instance and optionally parses an SQL string.
Parameters
Optional SQL string to parse during initialization.
Declaration
{
}
Description
Initializes the type list for valid SQL column types.
This function sets up an array of valid SQL column types, which will be used to validate column data types during parsing.
Declaration
array $haystack,
string $needle
) : bool
{
}
Description
Checks if a value exists in an array.
Parameters
The array to search.
The value to search for.
Return
Returns true if the needle is found in the haystack, otherwise false.
Declaration
string $field
) : bool
{
}
Description
Checks if a field is a primary key.
Parameters
The field definition.
Return
True if the field is a primary key, otherwise false.
Declaration
string $line
) : bool
{
}
Description
Checks if a field is auto-incremented.
Parameters
The field definition.
Return
True if the field is auto-incremented, otherwise false.
Declaration
string $sql
) : array
{
}
Description
Parses a CREATE TABLE SQL statement and extracts table and column information.
Parameters
The SQL string representing a CREATE TABLE statement.
Return
An array containing table name, columns, and primary key information.
Declaration
string $defaultValue
) : string|null
{
}
Description
Fixes and normalizes default values in SQL statements.
Parameters
The raw default value from SQL.
Return
The normalized default value or null if empty.
Declaration
string $type
) : bool
{
}
Description
Validates if a type is one of the known types.
Parameters
The data type to validate.
Return
True if the type is valid, otherwise false.
Declaration
string $attr
) : int|null
{
}
Description
Extracts the length for types that require it, such as varchar.
Parameters
The attributes of the field.
Return
The length of the field or null if not applicable.
Declaration
string $sql
)
{
}
Description
Parses multiple SQL statements.
Parameters
The SQL statements.
Declaration
string $sqlText
) : array
{
}
Description
Parses a SQL text, splits it into individual SQL queries, and processes them by handling delimiters, comments, and empty lines. It returns an array of queries, each with its delimiter.
This method processes the SQL text by:
- Normalizing newlines.
- Removing comment lines and empty lines.
- Splitting the SQL text into queries based on the delimiter.
- Handling multiple queries that may span across multiple lines.
- Changing the delimiter if a new one is specified within the SQL text.
Parameters
The input SQL text to be parsed.
Return
An array of queries, each containing the SQL query string and its corresponding delimiter.
Declaration
{
}
Description
Returns the table information parsed from the SQL statements.
Return
An array of parsed table information.
Declaration
{
}
Description
Get the value of tableInfo.
Return
The table information.
MagicObject\Util\Database\PicoTimeZoneChanger
Declaration
Methods
Declaration
string|DateTime|int $datetime,
string|DateTimeZone $from,
string|DateTimeZone $to
) : string|DateTime|int
{
}
Description
Changes the time from the source timezone to the target timezone, only if the timezones are different.
Parameters
The time in string format, DateTime object, or Unix timestamp (integer).
The source timezone (string or DateTimeZone object).
The target timezone (string or DateTimeZone object).
Return
The time adjusted to the target timezone, in the same format as the input.
Declaration
string|DateTime|int $datetime,
PicoDatabase $database
) : string|DateTime|int
{
}
Description
Adjusts the given time according to the timezone settings from the database configuration before saving to the database. The time is adjusted only if the database driver is either "sqlsrv" or "sqlite", and the source and target timezones are different.
This method is useful for ensuring that the time is correctly adjusted before being saved to the database, based on the application's time zone and the database's time zone settings.
Parameters
The time to be adjusted. Can be a string, DateTime object, or Unix timestamp (integer).
The database object containing the database configuration with timezones.
Return
The time adjusted to the target timezone, or the original datetime if no conversion is needed.
Declaration
string|DateTime|int $datetime,
PicoDatabase $database
) : string|DateTime|int
{
}
Description
Reverses the time zone conversion after reading data from the database. This function is useful for converting the time from the target timezone back to the original source timezone after the data has been fetched from the database. The time is adjusted only if the database driver is either "sqlsrv" or "sqlite", and the source and target timezones are different.
This method ensures that the time is returned to the correct timezone as per the application's settings, after being retrieved from the database.
Parameters
The time to be adjusted. Can be a string, DateTime object, or Unix timestamp (integer).
The database object containing the database configuration with timezones.
Return
The time adjusted to the source timezone, or the original datetime if no conversion is needed.
MagicObject\Util\Dms
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class Dms
This class provides methods to convert between Decimal Degrees and Degrees/Minutes/Seconds (DMS) formats. It also allows printing of these representations in a specified format.
Properties
Declaration
Description
Degree component.
Declaration
Description
Minute component.
Declaration
Description
Second component.
Declaration
Description
Decimal degree value.
Methods
Declaration
int $deg,
int $min,
float $sec
) : self
{
}
Description
Converts DMS (Degrees/Minutes/Seconds) to decimal format.
This method takes degree, minute, and second components and converts them to a decimal degree value.
Example:
<?php
$dms = new Dms();
$dms->dmsToDd(34, 15, 30);
echo $dms->printDd(); // Outputs: 34.258333
Parameters
Degree component.
Minute component.
Second component.
Return
Returns the current instance for method chaining.
Declaration
float $dec
) : self
{
}
Description
Converts decimal format to DMS (Degrees/Minutes/Seconds).
This method takes a decimal degree value and converts it to its DMS representation, storing the results in the instance variables.
Example:
<?php
$dms = new Dms();
$dms->ddToDms(34.258333);
echo $dms->printDms(); // Outputs: 34:15:30
Parameters
Decimal degree value.
Return
Returns the current instance for method chaining.
Declaration
bool $trim = false,
bool $rounded = false
) : string
{
}
Description
Prints the DMS (Degrees/Minutes/Seconds) representation.
This method outputs the DMS format as a string.
Parameters
Flag to indicate whether to trim leading zeros.
Flag to indicate whether to round the seconds.
Return
The DMS representation in "deg:min:sec" format.
Declaration
{
}
Description
Prints the decimal degree representation.
This method outputs the decimal degree format as a string.
Return
The decimal degree representation.
MagicObject\Util\File\FileUtil
Declaration
Package
MagicObject\Util\FileAuthors
- Kamshory
Links
Description
Class FileUtil
A utility class for handling file operations such as retrieving files from a directory and fixing file paths. This class cannot be instantiated due to its private constructor.
Methods
Declaration
string $directory,
int $level = 0,
string|null $origin = null
) : array
{
}
Description
Retrieves all files from a given directory, optionally at specified levels of depth. Returns the file paths relative to the original directory if a level greater than 0 is specified.
Parameters
The directory to scan for files.
The depth level for recursive scanning (default is 0).
The origin directory for relative path calculation.
Return
An array of file paths found within the specified directory.
Declaration
string $filePath
) : string
{
}
Description
Normalizes the file path by replacing any backslashes or forward slashes with the correct directory separator for the current platform.
Parameters
The file path to be normalized.
Return
The normalized file path.
MagicObject\Util\Image\ImageColor
Declaration
Package
MagicObject\Util\ImageAuthors
- Kamshory
Links
Description
Class ImageColor
Represents an RGB color and provides methods for manipulating and retrieving color information in various formats (hexadecimal, RGB). This class can also allocate the color to a given GD image resource for rendering.
Properties
Declaration
Description
Red component
Declaration
Description
Green component
Declaration
Description
Blue component
Methods
Declaration
int $red,
int $green,
int $blue
)
{
}
Description
Constructor
Parameters
Red component
Green component
Blue component
Declaration
GdImage $image
) : int
{
}
Description
Allocate color in the given image resource.
Parameters
The GD image resource.
Return
The color index of the allocated color.
Declaration
{
}
Description
Get color in hexadecimal format.
Return
The color represented as a hexadecimal string.
Declaration
{
}
Description
Get color in RGB format.
Return
The color represented as an RGB string.
Declaration
{
}
Description
Get the red component of the color.
Return
The red component.
Declaration
int $red
) : self
{
}
Description
Set the red component of the color.
Parameters
The red component.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the green component of the color.
Return
The green component.
Declaration
int $green
) : self
{
}
Description
Set the green component of the color.
Parameters
The green component.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the blue component of the color.
Return
The blue component.
Declaration
int $blue
) : self
{
}
Description
Set the blue component of the color.
Parameters
The blue component.
Return
Returns the current instance for method chaining.
MagicObject\Util\Image\ImageColorAlpha
Declaration
Package
MagicObject\Util\ImageAuthors
- Kamshory
Links
Description
Class ImageColorAlpha
Represents a color with an alpha channel for transparency in images.
Example:
<?php
$color = new ImageColorAlpha(255, 0, 0, 50); // Red with 50% opacity
Properties
Declaration
Description
The alpha value for the color (0 is fully opaque, 127 is fully transparent).
Declaration
Description
Red component
Declaration
Description
Green component
Declaration
Description
Blue component
Methods
Declaration
{
}
Description
Gets the alpha value of the color.
Return
The alpha value (0-127).
Declaration
{
}
Description
Gets the RGBA representation of the color as a string.
Return
The color in rgba format.
MagicObject\Util\Image\ImageExif
Declaration
Description
Class ImageExif
Provides functionality to extract and process EXIF data from images, particularly GPS coordinates. This class reads the EXIF metadata from an image file and retrieves the latitude and longitude, converting them from degrees, minutes, seconds (DMS) format to decimal format.
Methods
Declaration
string $imagePath
) : array|null
{
}
Description
Retrieves latitude and longitude from the EXIF data of an image.
This method checks if the image file exists, reads its EXIF data, and extracts the GPS coordinates (latitude and longitude) if available. The coordinates are returned in decimal format.
Parameters
The path to the image file.
Return
An array containing the latitude and longitude in decimal format, or null if GPS data is not available.
ImageResize
Declaration
Methods
Declaration
string $sourcePath,
string $destPath,
int $maxWidth,
int $maxHeight
) : void
{
}
Description
Resize an image while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Maximum width of the resized image.
Maximum height of the resized image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and crop the image from the center while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the cropped image.
Target height of the cropped image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and add padding to the image from the center while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the final image.
Target height of the final image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and crop the image from the top left while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the cropped image.
Target height of the cropped image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and add padding to the image from the top right while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the final image.
Target height of the final image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and crop the image from the top right while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the cropped image.
Target height of the cropped image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and crop the image from the bottom left while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the cropped image.
Target height of the cropped image.
Return
Declaration
string $sourcePath,
string $destPath,
int $targetWidth,
int $targetHeight
) : void
{
}
Description
Resize and crop the image from the bottom right while maintaining the aspect ratio.
Parameters
Path to the source image.
Path to save the resized image.
Target width of the cropped image.
Target height of the cropped image.
Return
Declaration
string $sourcePath,
string $destPath
) : void
{
}
Description
Flip the image vertically.
Parameters
Path to the source image.
Path to save the flipped image.
Return
Declaration
string $sourcePath,
string $destPath
) : void
{
}
Description
Flip the image horizontally.
Parameters
Path to the source image.
Path to save the flipped image.
Return
Declaration
string $sourcePath,
string $destPath
) : void
{
}
Description
Rotate the image by 90 degrees clockwise.
Parameters
Path to the source image.
Path to save the rotated image.
Return
Declaration
string $sourcePath,
string $destPath
) : void
{
}
Description
Rotate the image by 180 degrees.
Parameters
Path to the source image.
Path to save the rotated image.
Return
Declaration
string $sourcePath,
string $destPath
) : void
{
}
Description
Rotate the image by 270 degrees clockwise.
Parameters
Path to the source image.
Path to save the rotated image.
Return
Declaration
string $sourcePath,
string $watermarkPath,
string $outputPath,
int $opacity = 50,
string $position = 'bottom-right',
int $marginX = 10,
int $marginY = 10
) : bool
{
}
Description
Adds a watermark to an image.
Parameters
Path to the source image.
Path to the watermark image.
Path to save the resulting image.
Opacity of the watermark (0-100).
Position of the watermark (top-left, top-right, bottom-left, bottom-right, center).
Horizontal margin from the edge.
Vertical margin from the edge.
Return
True on success, false on failure.
MagicObject\Util\Image\ImageUtil
Declaration
Package
MagicObject\Util\ImageAuthors
- Kamshory
Links
Description
Class ImageUtil
A wrapper for the GD library in PHP. GD must be installed in your system for this to work.
Example:
<?php
$img = new Image('wheel.png');
$img->flip(1)->resize(120, 0)->save('wheel.jpg');
Constants
Properties
Declaration
Description
Image
Declaration
Description
Image
Declaration
Description
Image width
Declaration
Description
Image height
Methods
Declaration
int $width,
int $height,
ImageColor|null $color = null
) : self
{
}
Description
Creates an empty image with specified dimensions and color.
Parameters
The width of the new image.
The height of the new image.
Optional color to fill the image.
Return
Returns the current instance for method chaining.
Declaration
string|resource $imageFile
)
{
}
Description
Constructs an ImageUtil instance based on an image resource or file name.
Parameters
The path or URL to the image, or the image resource.
Throws
If the GD module is not installed or if the image file is invalid.
If the image file is not found or not readable.
Declaration
resource $resource
) : array
{
}
Description
Creates an ImageUtil instance from a resource.
Parameters
The image resource.
Return
Information about the image.
Throws
If the resource is invalid.
Declaration
string $imageFile
) : array
{
}
Description
Creates an ImageUtil instance from a file name.
Parameters
The path to the image file.
Return
Information about the image.
Throws
If the file is not found or not readable.
If the file is invalid.
Declaration
{
}
Description
Get the image width.
Return
Declaration
{
}
Description
Get the image height.
Return
Declaration
{
}
Description
Get the file name of the image.
Return
Declaration
GdImage|null $image = null
) : void
{
}
Description
Retain transparency for the image.
Parameters
The image resource to modify.
Return
Declaration
{
}
Description
Get the current image resource.
Return
Declaration
float $angle,
int $background = 0
) : $this
{
}
Description
Rotates the image to any direction using the given angle.
Parameters
The rotation angle, in degrees.
The background color for the rotated area.
Return
Throws
If the angle is not numeric.
Declaration
int $type
) : ImageUtil
{
}
Description
Mirrors the given image in the desired way.
Parameters
Direction of mirroring (1: Horizontal, 2: Vertical, 3: Both).
Return
Throws
If the flip type is invalid.
Declaration
int|null $newWidth = null,
int|null $newHeight = null
) : ImageUtil
{
}
Description
Resize the image to a new size.
Parameters
The new width of the image.
The new height of the image.
Return
Throws
If neither width nor height is valid.
Declaration
int $newSize,
ImageColor|null $color = null
) : ImageUtil
{
}
Description
Resize the image in a square format and maintain the aspect ratio.
Parameters
The new size of the image (width and height are equal).
Optional color to fill the extra space.
Return
Throws
If an error occurs during resizing.
Declaration
int $newX,
int $newY,
ImageColor|null $color = null
) : self
{
}
Description
Resizes the image while maintaining the aspect ratio.
Parameters
The new width.
The new height.
Optional color to fill the extra space.
Return
Returns the current instance for method chaining.
Throws
If an error occurs during resizing.
Declaration
ImageUtil|string $srcImage,
int $position = 3,
int $padding = 5,
int $opacity
) : self
{
}
Description
Stamps an image onto the current image.
Parameters
The image path or ImageUtil instance.
The position where the stamp will be placed.
The padding between the stamp and the edges.
The opacity of the stamp (0-100).
Return
Returns the current instance for method chaining.
Throws
If an error occurs during stamping.
If the source image is not found.
Declaration
string $text,
float[] $point,
float $size,
float $angle,
string $font,
int $maxwidth = 0,
float[]|null $rgbAr = null,
int $textAlignment = 1
)
{
}
Description
Writes text on the image.
Parameters
The text to write.
The coordinates to place the text (x, y).
The font size.
The angle of the text.
The path to the font file.
The maximum width of the text.
RGB array for text color.
The alignment of the text (left, center, right).
Throws
If the specified font is not found or if an error occurs.
Declaration
float $fromX,
float $fromY,
float $toX,
float $toY
) : self
{
}
Description
Crops the image from specified coordinates.
Parameters
The starting X coordinate.
The starting Y coordinate.
The ending X coordinate.
The ending Y coordinate.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Discards changes and restores the original image state.
Return
Returns the current instance for method chaining.
Declaration
ImageColor|null $color = null,
GdImage|null $image = null
) : $this|GdImage
{
}
Description
Makes a color transparent in the image.
Parameters
The color to make transparent.
The image resource to modify. If null, uses the current image.
Return
The modified image or the current instance.
Declaration
{
}
Description
Destroy the image to save the memory. Do this after all operations are complete.
MagicObject\Util\Image\ImageUtilException
Declaration
Package
MagicObject\Util\ImageAuthors
- Kamshory
Links
Description
Class ImageUtilException
Custom exception class for handling image-related errors in the MagicObject library.
Example:
<?php
throw new ImageUtilException("Error processing image", 500);
Properties
Declaration
Description
Previous exception
MagicObject\Util\Parsedown
Declaration
Description
Parsedown http://parsedown.org
(c) Emanuil Rusev http://erusev.com
For the full license information, view the LICENSE file that was distributed with this source code.
Constants
Properties
Declaration
Description
Flag indicating whether to enable line breaks in the parsed output.
Declaration
Description
Flag indicating whether to escape HTML markup in the parsed output.
Declaration
Description
Flag indicating whether to automatically link URLs in the parsed output.
Declaration
Description
Flag indicating whether to enable safe mode for handling links.
Declaration
Description
List of allowed protocols for safe mode links.
Declaration
Description
Array mapping block markers to their respective types.
Declaration
Description
List of block types that are unmarked.
Declaration
Description
Process inline elements within a line of text.
This method identifies and constructs inline elements based on their markers.
Parameters
The line of text to process.
An array of non-nestable inline types.
Return
The processed markup with inline elements.
Declaration
Description
@var array Holds instances of the class.
Declaration
Description
@var mixed Contains the definition data for reference links.
Declaration
Description
@var array List of special characters used in parsing.
Declaration
Description
@var array Regular expressions for strong emphasis syntax.
Declaration
Description
@var array Regular expressions for emphasis syntax.
Declaration
Description
@var string Regular expression for validating HTML attributes.
Declaration
Description
@var array List of void elements that do not have closing tags.
Declaration
Description
@var array List of text-level elements for inline formatting.
Methods
Declaration
string $text
) : string
{
}
Description
Parse the given Markdown text and convert it to HTML.
This method processes the input text by standardizing line breaks, removing surrounding line breaks, and splitting the text into lines, which are then processed to generate the final HTML markup.
Parameters
The Markdown text to parse.
Return
The converted HTML markup.
Declaration
bool $breaksEnabled
) : $this
{
}
Description
Enable or disable line breaks in the parsed output.
Parameters
Flag indicating whether to enable line breaks.
Return
Declaration
bool $markupEscaped
) : $this
{
}
Description
Escape HTML markup in the parsed output.
Parameters
Flag indicating whether to escape HTML markup.
Return
Declaration
bool $urlsLinked
) : $this
{
}
Description
Enable or disable automatic linking of URLs in the parsed output.
Parameters
Flag indicating whether to link URLs.
Return
Declaration
bool $safeMode
) : $this
{
}
Description
Enable or disable safe mode for handling links.
Parameters
Flag indicating whether to enable safe mode.
Return
Declaration
array $lines
) : string
{
}
Description
Process the lines of Markdown text to identify blocks and convert them to HTML.
This method analyzes the provided lines, identifies different block types, and constructs the corresponding HTML output.
Parameters
The lines of text to process.
Return
The generated HTML markup.
Declaration
string $type
) : bool
{
}
Description
Check if the specified block type can be continued.
Parameters
The type of the block to check.
Return
True if the block type can be continued, false otherwise.
Declaration
string $type
) : bool
{
}
Description
Check if a block type is completable.
This method checks if a method exists for completing a block of the specified type.
Parameters
The block type to check.
Return
True if the block type can be completed, false otherwise.
Declaration
array $line,
array|null $block = null
) : array|null
{
}
Description
Parse a code block from a line of text.
This method checks if the line represents the start of a code block and constructs the block if valid.
Parameters
The line of text to process.
The current block (if any).
Return
The constructed code block or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a code block.
This method appends additional lines to an existing code block.
Parameters
The line of text to process.
The current block being processed.
Return
The updated code block or null if not applicable.
Declaration
array $block
) : array
{
}
Description
Complete the code block.
This method finalizes the formatting of a completed code block.
Parameters
The block to complete.
Return
The completed code block.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a fenced code block.
This method appends additional lines to an existing fenced code block.
Parameters
The line of text to process.
The current fenced code block being processed.
Return
The updated fenced code block or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse a comment block from a line of text.
This method checks if the line represents a comment block and constructs it if valid.
Parameters
The line of text to process.
Return
The constructed comment block or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a comment block.
This method appends additional lines to an existing comment block.
Parameters
The line of text to process.
The current comment block being processed.
Return
The updated comment block or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse a fenced code block from a line of text.
This method checks if the line represents the start of a fenced code block and constructs the block if valid.
Parameters
The line of text to process.
Return
The constructed fenced code block or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue parsing a fenced code block from subsequent lines.
This method handles additional lines that continue the fenced code block. It appends the text to the block until it is completed or interrupted.
Parameters
The current line of text being processed.
The existing fenced code block being built.
Return
The updated fenced code block or null if it remains incomplete.
Declaration
array $block
) : array
{
}
Description
Complete the fenced code block.
This method finalizes the formatting of a completed fenced code block.
Parameters
The fenced code block to complete.
Return
The completed fenced code block.
Declaration
array $line
) : array|null
{
}
Description
Parse a list from a line of text.
This method checks if the line represents a list item and constructs the list block if valid.
Parameters
The line of text to process.
Return
The constructed list block or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a list.
This method appends additional items to an existing list block.
Parameters
The line of text to process.
The current list block being processed.
Return
The updated list block or null if not applicable.
Declaration
array $block
) : array
{
}
Description
Complete the list block.
This method finalizes the formatting of a completed list block.
Parameters
The list block to complete.
Return
The completed list block.
Declaration
array $line
) : array|null
{
}
Description
Parse a block quote from a line of text.
This method checks if the line starts with a '>' character and captures the quote text.
Parameters
The line of text to process.
Return
The constructed blockquote or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a block quote.
This method appends additional lines to an existing block quote if they start with a '>'.
Parameters
The line of text to process.
The current block quote being processed.
Return
The updated block quote or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse a horizontal rule from a line of text.
This method checks for repeated characters to determine if a horizontal rule is present.
Parameters
The line of text to process.
Return
The constructed horizontal rule or null if not applicable.
Declaration
array $line,
array|null $block = null
) : array|null
{
}
Description
Parse a Setext header from a line of text.
This method constructs a header based on the presence of underlining characters.
Parameters
The line of text to process.
The current block being processed.
Return
The updated block or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse custom markup from a line of text.
This method constructs a block based on the presence of HTML-like tags.
Parameters
The line of text to process.
Return
The constructed markup block or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse a reference link definition from a line of text.
This method constructs a reference link that can be used later in the document.
Parameters
The line of text to process.
Return
The constructed reference or null if not applicable.
Declaration
array $line
) : array|null
{
}
Description
Parse a reference link definition from a line of text.
This method constructs a reference link that can be used later in the document.
Parameters
The line of text to process.
Return
The constructed reference or null if not applicable.
Declaration
array $line,
array|null $block = null
) : array|null
{
}
Description
Parse a table header from a line of text.
This method checks if the line represents a table structure and constructs it if valid.
Parameters
The line of text to process.
The current block being processed.
Return
The constructed table block or null if not applicable.
Declaration
array $line,
array $block
) : array|null
{
}
Description
Continue processing a table.
This method appends additional rows to an existing table block.
Parameters
The line of text to process.
The current table block being processed.
Return
The updated table block or null if not applicable.
Declaration
array $line
) : array
{
}
Description
Parse a paragraph from a line of text.
This method constructs a paragraph block from the provided text.
Parameters
The line of text to process.
Return
The constructed paragraph block.
Declaration
string $text,
array $nonNestables = array ( )
) : string
{
}
Description
Process a line of text and convert inline elements.
This method identifies markers in the text and processes them into HTML-like structures.
Parameters
The line of text to process.
An array of non-nestable inline types.
Return
The processed markup with inline elements.
Declaration
array $excerpt
) : array|null
{
}
Description
Parse inline code from the excerpt.
This method checks for code markers and captures the code content.
Parameters
The excerpt to process.
Return
The inline code element or null if not applicable.
Declaration
array $excerpt
) : array|null
{
}
Description
Parse an email tag from the excerpt.
This method identifies email addresses formatted within angle brackets.
Parameters
The excerpt to process.
Return
The email link element or null if not applicable.
Declaration
array $excerpt
) : array|null
{
}
Description
Parse emphasis (bold/italic) from the excerpt.
This method checks for markers indicating strong or emphasized text.
Parameters
The excerpt to process.
Return
The emphasis element or null if not applicable.
Declaration
array $excerpt
) : array|null
{
}
Description
Handle escape sequences for special characters.
This method checks for special characters that are preceded by a backslash.
Parameters
The excerpt to process.
Return
The escaped character element or null if not applicable.
Declaration
array $excerpt
) : array|null
{
}
Description
Parse an inline image from the excerpt.
This method identifies image links formatted with brackets and captures the source and alt text.
Parameters
The excerpt to process.
Return
The image element or null if not applicable.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline links in the provided text.
Parameters
Contains the text to be processed.
Return
Returns an array containing the extent of the match and the link element, or null if no match is found.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline HTML markup in the provided text.
Parameters
Contains the text to be processed.
Return
Returns an array with the markup and its extent, or null if no valid markup is found.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline special characters in the provided text.
Parameters
Contains the text to be processed.
Return
Returns an array with the escaped character and its extent, or null if no special character is found.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline strikethrough text in the provided text.
Parameters
Contains the text to be processed.
Return
Returns an array with the extent of the strikethrough and the corresponding element, or null if no match is found.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline URLs in the provided text.
Parameters
Contains the text to be processed.
Return
Returns an array with the extent and URL element, or null if no valid URL is found.
Declaration
array $excerpt
) : array|null
{
}
Description
Processes inline URL tags formatted in angle brackets.
Parameters
Contains the text to be processed.
Return
Returns an array with the extent and URL element, or null if no valid tag is found.
Declaration
string $text
) : string
{
}
Description
Processes unmarked text by converting line breaks to HTML.
Parameters
The text to be processed.
Return
The processed text with line breaks converted to HTML.
Declaration
array $element
) : string
{
}
Description
Generates HTML markup for a given element.
Parameters
The element to be rendered as HTML.
Return
The generated HTML markup for the element.
Declaration
array $elements
) : string
{
}
Description
Generates HTML markup for multiple elements.
Parameters
An array of elements to be rendered as HTML.
Return
The generated HTML markup for all elements.
Declaration
array $lines
) : string
{
}
Description
Processes list items by converting lines to HTML list markup.
Parameters
An array of lines representing list items.
Return
The generated HTML for the list items.
Declaration
string $text
) : string
{
}
Description
Parses the input text and returns the generated HTML markup.
Parameters
The text to be parsed.
Return
The generated HTML markup.
Declaration
array $element
) : array
{
}
Description
Sanitizes an HTML element to prevent XSS vulnerabilities.
Parameters
The element to be sanitized.
Return
The sanitized element.
Declaration
array $element,
string $attribute
) : array
{
}
Description
Filters unsafe URLs in a given attribute of an HTML element.
Parameters
The element containing the attribute to be filtered.
The name of the attribute to be checked.
Return
The element with the filtered attribute.
Declaration
string $text,
bool $allowQuotes = false
) : string
{
}
Description
Escapes special characters for HTML output.
Parameters
The text to be escaped.
Whether to allow unescaped quotes.
Return
The escaped text.
Declaration
string $string,
string $needle
) : bool
{
}
Description
Checks if a string starts with a given needle.
Parameters
The string to be checked.
The substring to check for.
Return
True if the string starts with the needle, false otherwise.
Declaration
string $name = 'default'
) : static
{
}
Description
Retrieves an instance of the class.
Parameters
The name of the instance.
Return
The instance of the class.
MagicObject\Util\PicoArrayUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoArrayUtil
Utility class for performing various array operations, particularly key transformations between camelCase and snake_case formats.
This class provides static methods and cannot be instantiated.
Methods
Declaration
array|object|stdClass $input
) : array
{
}
Description
Converts the keys of an array or object to camelCase.
This method can process both associative arrays and objects.
Example:
<?php
$data = ['first_name' => 'John', 'last_name' => 'Doe'];
$camelized = PicoArrayUtil::camelize($data);
// $camelized is ['firstName' => 'John', 'lastName' => 'Doe']
Parameters
Array or object containing data to be processed.
Return
Processed array with camelCase keys.
Declaration
array|object|stdClass $input
) : array
{
}
Description
Converts the keys of an array or object to snake_case.
This method can process both associative arrays and objects.
Example:
<?php
$data = ['firstName' => 'John', 'lastName' => 'Doe'];
$snakeized = PicoArrayUtil::snakeize($data);
// $snakeized is ['first_name' => 'John', 'last_name' => 'Doe']
Parameters
Array or object containing data to be processed.
Return
Processed array with snake_case keys.
Declaration
array
) : void
{
}
Description
Recursively converts array keys to camelCase.
This method operates by reference to avoid unnecessary copies.
Parameters
Array containing data to be processed by reference.
Return
Declaration
array
) : void
{
}
Description
Recursively converts array keys to snake_case.
This method operates by reference to avoid unnecessary copies.
Parameters
Array containing data to be processed by reference.
Return
Declaration
array $array
) : array
{
}
Description
Recursively normalizes array indices by converting string integer keys into numeric sequential indices, while retaining non-integer keys.
This method processes multi-dimensional arrays of unlimited depth. If a key is a string that represents an integer (e.g., "0", "1"), it is converted into a numeric sequential index. Non-integer or non-string keys remain unchanged.
Parameters
The input array to normalize.
Return
The normalized array with modified indices.
Declaration
array
) : void
{
}
Description
Recursively converts string "true"/"false"/"null" to actual boolean/null values and converts numeric string keys to integer keys.
This function will iterate over each element of the given array and perform the following:
- Converts string
"true"to booleantrue, string"false"to booleanfalse, and string"null"to thenullvalue. - Converts string keys representing numbers (e.g., "0", "1", "2") into actual integers (e.g., 0, 1, 2).
- Recursively processes nested arrays if present.
Parameters
The input array which will be modified in-place. The function updates
Return
This function modifies the array by reference and does not return any value.
MagicObject\Util\PicoCurlUtil
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class PicoCurlUtil
This class provides an interface for making HTTP requests using cURL.
Properties
Declaration
Description
cURL handle
Declaration
Description
Response headers from the last request
Declaration
Description
Response body from the last request
Declaration
Description
HTTP status code from the last request
Methods
Declaration
{
}
Description
PicoCurlUtil constructor. Initializes the cURL handle.
Declaration
int $option,
mixed $value
)
{
}
Description
Sets a cURL option.
Parameters
cURL option to set
Value for the cURL option
Declaration
bool $verify
)
{
}
Description
Enables or disables SSL verification.
Parameters
If true, SSL verification is enabled; if false, it is disabled.
Declaration
string $url,
array $headers = array ( )
) : string
{
}
Description
Executes a GET request.
Parameters
URL for the request
Additional headers for the request
Return
Response body
Throws
If an error occurs during cURL execution
Declaration
string $url,
mixed $data,
array $headers = array ( )
) : string
{
}
Description
Executes a POST request.
Parameters
URL for the request
Data to send
Additional headers for the request
Return
Response body
Throws
If an error occurs during cURL execution
Declaration
string $url,
mixed $data,
array $headers = array ( )
) : string
{
}
Description
Executes a PUT request.
Parameters
URL for the request
Data to send
Additional headers for the request
Return
Response body
Throws
If an error occurs during cURL execution
Declaration
string $url,
array $headers = array ( )
) : string
{
}
Description
Executes a DELETE request.
Parameters
URL for the request
Additional headers for the request
Return
Response body
Throws
If an error occurs during cURL execution
Declaration
{
}
Description
Executes the cURL request and processes the response.
Return
Response body
Throws
If an error occurs during cURL execution
Declaration
{
}
Description
Gets the HTTP status code from the last response.
Return
HTTP status code
Declaration
{
}
Description
Gets the response headers from the last request.
Return
Array of response headers
Declaration
{
}
Description
Closes the cURL handle.
Declaration
{
}
Description
Destructor to close cURL when the object is destroyed.
MagicObject\Util\PicoDateTimeUtil
Declaration
Package
MagicObjectAuthors
- Kamshory
Links
Description
Class PicoDateTimeUtil
A utility class for parsing date and time strings into DateTime objects. This class provides methods to convert various date formats into a standardized DateTime object for easier manipulation and formatting.
It supports multiple date formats, including ISO 8601 and RFC 2822, as well as local and custom formats and Unix timestamps.
Methods
Declaration
string|int $dateString
) : DateTime|null
{
}
Description
Parse DateTime from a string or Unix timestamp.
This method attempts to parse a given date string or Unix timestamp into a DateTime object using multiple predefined formats. If the parsing is successful, it returns the corresponding DateTime object; otherwise, it returns null.
Parameters
The date string or Unix timestamp to be parsed.
Return
Returns a DateTime object if parsing is successful,
MagicObject\Util\PicoEnvironmentVariable
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoEnvironmentVariable
A utility class for handling environment variable replacements within strings and data structures.
Methods
Declaration
array|object $values,
array $collection,
bool $recursive = false
) : array|object
{
}
Description
Replace all values in a collection with other properties.
Parameters
Values to process.
Collection of replacement values.
Flag indicating if the process should be recursive.
Return
Processed values with replacements applied.
Declaration
array $values,
array $collection,
bool $recursive = false
) : array
{
}
Description
Replace all values in an array with other properties.
Parameters
Values to process.
Collection of replacement values.
Flag indicating if the process should be recursive.
Return
Processed array with replacements applied.
Declaration
stdClass|object $values,
array $collection,
bool $recursive = false
) : stdClass|object
{
}
Description
Replace all values in an object with other properties.
Parameters
Values to process.
Collection of replacement values.
Flag indicating if the process should be recursive.
Return
Processed object with replacements applied.
Declaration
string $value,
array $collection
) : mixed
{
}
Description
Replace strings with environment variable names from a string.
Parameters
Value to process.
Collection of replacement values.
Return
Processed value with replacements applied.
Declaration
string $key,
array $collection
) : mixed|null
{
}
Description
Retrieve a value from the collection by its key.
Parameters
Key name to retrieve.
Collection to search in.
Return
Retrieved value or null if not found.
Declaration
array $values,
bool $recursive = false
) : array
{
}
Description
Replace all values in an array with environment variable names.
Parameters
Values to process.
Flag indicating if the process should be recursive.
Return
Processed values with replacements applied.
Declaration
string $value
) : string
{
}
Description
Replace strings with environment variable names from a string.
Parameters
Value to process.
Return
Processed value with replacements applied.
Declaration
string $value
) : string
{
}
Description
Replace a value with its corresponding environment variable.
Parameters
Value to process.
Return
Processed value with replacements applied.
Declaration
string $value
) : array
{
}
Description
Extract environment variable names from a string.
Parameters
Value to process.
Return
List of variable names extracted.
MagicObject\Util\PicoGenericObject
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoGenericObject
A generic object that allows dynamic property management. This class extends stdClass and provides methods to load, set, get, unset, and check properties dynamically.
Properties can be accessed using camelCase naming conventions.
Methods
Declaration
MagicObject|self|stdClass|array|null $data = null
)
{
}
Description
Constructor
Initializes the object with optional initial data.
Parameters
Initial data to load into the object.
Declaration
stdClass|array $data
) : self
{
}
Description
Load data into the object.
Accepts either an associative array or an object, converting its keys to camelCase format before loading.
Example:
<?php
$obj = new PicoGenericObject();
$obj->loadData(['first_name' => 'John', 'last_name' => 'Doe']);
echo $obj->get('firstName'); // Outputs: John
Parameters
Data to be loaded.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName,
mixed $propertyValue
) : self
{
}
Description
Set a property value.
Converts the property name to camelCase and assigns the value.
Example:
<?php
$obj = new PicoGenericObject();
$obj->set('first_name', 'John');
echo $obj->get('firstName'); // Outputs: John
Parameters
Name of the property.
Value to set.
Return
Returns the current instance for method chaining.
Declaration
string $propertyName
) : mixed|null
{
}
Description
Get a property value.
Retrieves the value of a property, returning null if not set.
Example:
<?php
$value = $obj->get('firstName'); // Retrieves the value of 'firstName'
Parameters
Name of the property.
Return
The value of the property or null if not set.
Declaration
string $name,
mixed $value
) : void
{
}
Description
Magic method to set property values dynamically.
This method allows setting properties without directly calling set().
Example:
<?php
$obj->firstName = 'John'; // Calls __set() internally
Parameters
Name of the property.
Value to set.
Return
Declaration
string $name
) : mixed|null
{
}
Description
Magic method to get property values dynamically.
This method allows getting properties without directly calling get().
Example:
<?php
$value = $obj->firstName; // Calls __get() internally
Parameters
Name of the property to get.
Return
The value stored in the property or null if not set.
Declaration
string $name
) : bool
{
}
Description
Check if a property is set.
Example:
<?php
if ($obj->issetFirstName()) {
// Do something
}
Parameters
Name of the property.
Return
True if the property is set, false otherwise.
Declaration
string $name
) : self
{
}
Description
Unset a property value.
Example:
<?php
$obj->unsetFirstName(); // Removes the property 'firstName'
Parameters
Name of the property.
Return
Returns the current instance for method chaining.
Declaration
string $method,
array $params
) : mixed|null
{
}
Description
Magic method called when invoking undefined methods.
This method handles dynamic method calls for property management.
Supported methods:
-
isset<PropertyName>: Checks if the property is set.- Example:
$obj->issetFoo()returns true if propertyfoois set.
- Example:
-
is<PropertyName>: Checks if the property is set and equals 1 (truthy).- Example:
$obj->isFoo()returns true if propertyfoois set and is equal to 1.
- Example:
-
get<PropertyName>: Retrieves the value of the property.- Example:
$value = $obj->getFoo()gets the value of propertyfoo.
- Example:
-
set<PropertyName>: Sets the value of the property.- Example:
$obj->setFoo($value)sets the propertyfooto$value.
- Example:
-
unset<PropertyName>: Unsets the property.- Example:
$obj->unsetFoo()removes the propertyfoo.
- Example:
Parameters
Method name.
Parameters for the method.
Return
The result of the method call or null if not applicable.
MagicObject\Util\PicoHttpCache
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoHttpCache
A utility class for managing HTTP caching headers.
This class provides methods to set cache lifetime for HTTP responses.
Methods
Declaration
int $lifetime
) : void
{
}
Description
Send headers to the browser to cache the current URL.
This method sets the appropriate headers for caching, including the expiration date and cache control directives.
Parameters
Cache lifetime in seconds.
Return
Throws
if $lifetime is negative.
MagicObject\Util\PicoIniUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Utility class for handling INI file operations.
This class provides methods for reading from and writing to INI files, as well as parsing INI strings into arrays and vice versa.
Methods
Declaration
array $array,
string $path
) : bool
{
}
Description
Write an array to an INI file.
This method converts an array into an INI format and saves it to the specified file path.
Parameters
The array to write to the INI file.
The file path where the INI file will be saved.
Return
True on success, false on failure.
Declaration
string $content,
array $array
) : string
{
}
Description
Generate INI content from a simple array.
Parameters
The existing content (usually empty).
The array to convert to INI format.
Return
The formatted INI content.
Declaration
string $content,
array $array
) : string
{
}
Description
Generate INI content from a multidimensional array.
Parameters
The existing content (usually empty).
The multidimensional array to convert to INI format.
Return
The formatted INI content.
Declaration
string $path
) : array|false
{
}
Description
Parse an INI file from the specified path.
Parameters
The file path of the INI file to parse.
Return
The parsed INI data as an array, or false on failure.
Declaration
string $str
) : array|false
{
}
Description
Parse an INI string into an array.
Parameters
The INI string to parse.
Return
The parsed INI data as an array, or false on failure.
Declaration
string $line
) : bool
{
}
Description
Check if the line is invalid (empty or a comment).
Parameters
The line to check.
Return
True if the line is invalid, false otherwise.
Declaration
string $line
) : bool
{
}
Description
Check if a line is invalid.
A line is considered invalid if it is empty or starts with a comment character (# or ;).
Parameters
The line to check.
Return
True if the line is invalid, false otherwise.
Declaration
string $value
) : string
{
}
Description
Remove surrounding quotes from a value.
This method checks if the given value is surrounded by either double or single quotes and removes those quotes if they are present.
Parameters
The value to fix.
Return
The cleaned value without surrounding quotes.
Declaration
string $value
) : string
{
}
Description
Remove surrounding quotes from a value using regex.
This method checks if the given value matches the pattern of being surrounded by double or single quotes and removes them if so.
Parameters
The value to fix.
Return
The cleaned value without surrounding quotes.
Declaration
array $ret,
string $insideSection,
string $arrName,
array $matches,
mixed $value
) : array
{
}
Description
Fix and organize the value in the parsed result.
This method ensures that the provided array is correctly formatted based on the given parameters, handling nested structures as needed.
Parameters
The parsed result array to update.
The name of the current section.
The name of the array key to update.
Matches found during parsing.
The value to assign to the array.
Return
The updated parsed result array.
MagicObject\Util\PicoLocale
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Locale
The PicoLocale class serves as a container for a collection of predefined locale constants.
These constants represent different locale identifiers for various countries, regions, and languages, using the format of language-region (e.g., "en_US" for English in the United States, "fr_FR" for French in France).
Each constant corresponds to a specific locale, which can be used in applications to handle internationalization (i18n), localization (l10n), and formatting of data such as dates, currencies, and numbers, based on the user's regional settings.
Constants
Methods
MagicObject\Util\PicoPasswordUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoPasswordUtil
A utility class for handling password management tasks, including validation, hashing, and enforcing security policies.
This class provides methods to validate passwords based on customizable rules, including minimum length and complexity requirements. It also offers functionality to hash passwords using various cryptographic algorithms to ensure secure storage.
Passwords can be validated against a regular expression that enforces specific character types (uppercase, lowercase, numbers, and special characters). Users can configure the minimum length and the hashing algorithm used to generate password hashes.
Example usage:
$passwordUtil = new PicoPasswordUtil();
$passwordUtil->validate('YourSecureP@ssw0rd!');
$hashedPassword = $passwordUtil->getHash('YourSecureP@ssw0rd!');
Constants
Properties
Declaration
Description
Regular expression format for password validation.
This regex is used to enforce complexity rules for passwords, including the presence of uppercase letters, lowercase letters, numbers, and special characters.
Declaration
Description
Minimum length of the password.
This sets the minimum number of characters required for a valid password.
Declaration
Description
Hash algorithm to be used for password hashing.
This determines which hashing algorithm will be applied when generating password hashes.
Methods
Declaration
string|null $hashAlgorithm = null,
int $minLength = 8,
string|null $regex = null
)
{
}
Description
Constructor to initialize password utility settings.
Parameters
Optional hashing algorithm to use.
Minimum length of the password. Default is 8.
Optional regex pattern for password validation.
Declaration
{
}
Description
Get the regular expression string used for password validation.
The method replaces the placeholder '%d' with the minimum length defined for the password.
Return
The regex string with the minimum length.
Declaration
string $password
) : bool
{
}
Description
Validate the given password against the set rules.
This method checks if the password meets the length requirement and matches the defined complexity rules. Throws an exception if the password is invalid.
Parameters
Password to be validated.
Return
True if the password is valid.
Throws
If the password is invalid.
Declaration
string $password,
bool $binary = false,
bool $validate = true
) : string
{
}
Description
Get the hash of the given plain text password.
This method hashes the password using the specified hashing algorithm. Optionally validates the password before hashing.
Parameters
Plain text password to be hashed.
Optional. If true, returns the binary representation of the hash.
Optional. If true, validates the password before hashing.
Return
The resulting hashed password.
Throws
If the password is invalid and validation is enabled.
Declaration
{
}
Description
Get the current regular expression format used for password validation.
Return
The current regex format.
Declaration
string $regex
) : self
{
}
Description
Set a new regular expression format for password validation.
Parameters
New regular expression format.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the minimum length required for passwords.
Return
The minimum length for passwords.
Declaration
int $minLength
) : self
{
}
Description
Set a new minimum length requirement for passwords.
Parameters
New minimum length for passwords.
Return
Returns the current instance for method chaining.
Declaration
{
}
Description
Get the currently set hash algorithm.
Return
The hashing algorithm in use.
Declaration
string $hashAlgorithm
) : self
{
}
Description
Set a new hash algorithm to be used for password hashing.
Parameters
New hashing algorithm.
Return
Returns the current instance for method chaining.
MagicObject\Util\PicoStringUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoStringUtil
A utility class for performing various string manipulations and transformations.
This class provides static methods for converting between different string case formats (snake case, camel case, kebab case), validating string contents, and manipulating strings (trimming, checking for null/empty values, etc.).
The methods are designed to be used statically, allowing for convenient access without needing to instantiate the class.
Example usage:
<?php
$camelCase = PicoStringUtil::camelize('example_string');
$kebabCase = PicoStringUtil::kebapize('exampleString');
$isNotEmpty = PicoStringUtil::isNotNullAndNotEmpty('Some Value');
Methods
Declaration
string $input,
string $glue = '_'
) : string
{
}
Description
Convert snake case to camel case
Parameters
Input string in snake case format.
Optional. The glue character used in the input string (default is '_').
Return
Converted string in camel case format.
Declaration
string $input,
string $glue = '_'
) : string
{
}
Description
Convert snake case to upper camel case
Parameters
Input string in snake case format.
Optional. The glue character used in the input string (default is '_').
Return
Converted string in upper camel case format.
Declaration
string $input,
string $glue = '_'
) : string
{
}
Description
Convert camel case to snake case
Converts a string from camel case (e.g., exampleString) to snake case (e.g., example_string).
Parameters
Input string in camel case format.
Optional. The glue character used in the input string (default is '_').
Return
Converted string in snake case format.
Declaration
mixed $object
) : mixed
{
}
Description
Snakeize object
Converts all keys of an object or an array to snake case. This is useful for normalizing data structures when working with APIs or databases.
Parameters
Object or array to be converted.
Return
The input object/array with keys converted to snake case.
Declaration
string $input,
string $glue = '_'
) : string
{
}
Description
Convert snake case to title case
Converts a snake case string (e.g., example_string) to title case (e.g., Example String). Words are separated by spaces, and the first letter of each word is capitalized.
Parameters
Input string in snake case format.
Optional. The glue character used in the input string (default is '_').
Return
Converted string in title case format.
Declaration
string $input
) : string
{
}
Description
Convert camel case to title case
Converts a camel case string (e.g., exampleString) to title case (e.g., Example String).
Parameters
Input string in camel case format.
Return
Converted string in title case format.
Declaration
string $input
) : string
{
}
Description
Convert to kebab case
Converts a string to kebab case (e.g., example_string becomes example-string). Useful for URL slugs or CSS class names.
Parameters
Input string in any case format.
Return
Converted string in kebab case format.
Declaration
string $input
) : string
{
}
Description
Create constant key
Converts a string to a constant key format (e.g., example_string becomes EXAMPLE_STRING).
Parameters
Input string in snake case format.
Return
Converted string in uppercase snake case format.
Declaration
string $haystack,
string $value,
bool $caseSensitive = false
) : bool
{
}
Description
Check if string starts with a substring
Determines if the given string starts with the specified substring. Comparison can be case-sensitive or case-insensitive.
Parameters
The string to check.
The substring to look for at the start.
Optional. Flag to indicate if the comparison is case-sensitive (default is false).
Return
True if the string starts with the substring, false otherwise.
Declaration
string $haystack,
string $value,
bool $caseSensitive = false
) : bool
{
}
Description
Check if string ends with a substring
Determines if the given string ends with the specified substring. Comparison can be case-sensitive or case-insensitive.
Parameters
The string to check.
The substring to look for at the end.
Optional. Flag to indicate if the comparison is case-sensitive (default is false).
Return
True if the string ends with the substring, false otherwise.
Declaration
string $haystack,
string $substring,
int $count = -1
) : string
{
}
Description
Left trim a string
Trims the specified substring from the start of the string for a defined number of times. If count is -1, it trims until the substring no longer occurs at the start.
Parameters
The string to trim.
The substring to trim from the start.
Optional. Number of times to trim (default is -1).
Return
The trimmed string.
Declaration
string $haystack,
string $substring,
int $count = -1
) : string
{
}
Description
Right trim a string
Trims the specified substring from the end of the string for a defined number of times. If count is -1, it trims until the substring no longer occurs at the end.
Parameters
The string to trim.
The substring to trim from the end.
Optional. Number of times to trim (default is -1).
Return
The trimmed string.
Declaration
string $value
) : bool
{
}
Description
Check if string is not null and not empty
Determines if the given string is neither null nor empty.
Parameters
The string to check.
Return
True if the string is not null and not empty, false otherwise.
Declaration
string $value
) : bool
{
}
Description
Check if string is null or empty
Determines if the given string is either null or empty.
Parameters
The string to check.
Return
True if the string is null or empty, false otherwise.
Declaration
mixed $value1,
mixed $value2
) : mixed
{
}
Description
Select not null value
Returns the first value that is not null from the two provided values.
Parameters
The first value to check.
The second value to check.
Return
The first non-null value.
Declaration
string $input
) : string
{
}
Description
Fix carriage returns in a string
Normalizes line endings in a string to Windows-style carriage return line feed (CRLF).
Parameters
The input string to fix.
Return
The modified string with normalized line endings.
Declaration
string $input,
int $length = 76,
string $delimiter = ' '
) : string
{
}
Description
Splits a string into chunks of a specified length without breaking words.
This method ensures that words are not split between chunks, making it ideal for scenarios where maintaining the integrity of words is crucial. The chunks are separated by the specified delimiter.
Parameters
The input string to be chunked.
The maximum length of each chunk. Defaults to 76.
The delimiter to append between chunks. Defaults to "\n".
Return
The chunked string with the specified delimiter between chunks.
MagicObject\Util\PicoTableUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Utility class for handling DOM element operations related to tables.
This class provides methods for setting attributes, class names, and identity properties on DOM elements, as well as parsing attribute strings into associative arrays. It is designed to facilitate the management of table-related DOM elements within the MagicObject framework.
Methods
Declaration
DOMElement $node,
array $classList
) : DOMElement
{
}
Description
Set the class list for a DOMElement.
Parameters
The DOM node to modify.
An array of class names to set.
Return
The modified DOM node.
Declaration
DOMElement $node,
array $annotationAttributes
) : DOMElement
{
}
Description
Set attributes for a DOMElement.
Parameters
The DOM node to modify.
An associative array of attributes to set.
Return
The modified DOM node.
Declaration
DOMElement $node,
PicoGenericObject $identity
) : DOMElement
{
}
Description
Set the identity for a DOMElement.
Parameters
The DOM node to modify.
The identity object.
Return
The modified DOM node.
Declaration
string $attributes
) : array
{
}
Description
Parse attributes from a string representation.
Parameters
The string containing attributes.
Return
An associative array of parsed attributes.
Throws
If the provided attributes is an array.
Declaration
string $className
) : bool
{
}
Description
Validate the class name of a DOMElement.
Parameters
The class name to validate.
Return
True if the class name is valid, false otherwise.
MagicObject\Util\PicoTestValueUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoTestValueUtil
A utility class for managing return values based on specified conditions. This class allows you to set a return value and control whether it should be returned based on conditions. It is useful for testing and mocking scenarios where specific outputs are required based on input conditions.
Properties
Declaration
Description
Value to be returned.
Declaration
Description
Condition for determining return value.
Methods
Declaration
mixed $returnValue
) : self|mixed
{
}
Description
Set a return value.
Parameters
The value to return based on the condition.
Return
Returns the return value if the condition is true; otherwise, returns the instance.
Declaration
{
}
Description
Set return value to 'selected'.
Return
Returns 'selected' if the condition is true; otherwise, returns the instance.
Declaration
{
}
Description
Set return value to ' selected=selected'.
Return
Returns ' selected=selected' if the condition is true; otherwise, returns the instance.
Declaration
{
}
Description
Set return value to 'checked'.
Return
Returns 'checked' if the condition is true; otherwise, returns the instance.
Declaration
{
}
Description
Set return value to ' checked=checked'.
Return
Returns ' checked=checked' if the condition is true; otherwise, returns the instance.
Declaration
mixed $returnValue
) : mixed|null
{
}
Description
Set a return value and determine if it should be returned.
Parameters
The value to return if the condition is true.
Return
Returns the return value if the condition is true; otherwise, returns null.
Declaration
bool $condition
) : self|mixed
{
}
Description
Set the condition for returning the value.
Parameters
The condition that determines the return value.
Return
Returns the return value if set and the condition is true; otherwise, returns the instance.
Declaration
mixed $param1,
mixed $param2
) : self|mixed
{
}
Description
Set the condition based on equality of two parameters.
Parameters
The first parameter to compare.
The second parameter to compare.
Return
Returns the return value if set and the parameters are equal; otherwise, returns the instance.
MagicObject\Util\PicoYamlUtil
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class PicoYamlUtil
A utility class for handling YAML operations, including converting arrays to YAML strings and determining the depth of nested arrays.
This class is intended to be used statically and cannot be instantiated.
Methods
Declaration
array $array
) : int
{
}
Description
Get the depth of a nested array.
This method recursively calculates how deep the given array is.
Example:
<?php
$array = [1, [2, [3, 4]]];
$depth = PicoYamlUtil::arrayDepth($array); // Returns 3
Parameters
The array to be checked for depth.
Return
The depth of the array. Returns 0 for non-array input, 1 for empty arrays.
Declaration
mixed $input,
int|null $inline,
int $indent,
int $flags
) : string
{
}
Description
Dumps a PHP value to a YAML string.
This method converts a PHP array (or other types) into a YAML-formatted string. It allows customization of the inline representation, indentation, and flags for serialization.
Example:
<?php
$data = ['name' => 'John', 'age' => 30];
$yaml = PicoYamlUtil::dump($data, null, 4, 0);
Parameters
The PHP value to be converted to YAML.
The level at which to switch to inline YAML.
The number of spaces to use for indentation of nested nodes.
A bit field of DUMP_* constants to customize the dumped YAML string.
Return
A YAML string representing the original PHP value.
Declaration
string $file
) : mixed
{
}
Description
Parse a YAML file and return the parsed data.
This function loads a YAML file and returns the parsed content as an array or object depending on the configuration of the YAML parser.
Parameters
The path to the YAML file that needs to be parsed.
Return
The parsed YAML data, typically as an array or object.
Throws
If the file cannot be loaded or parsed.
Declaration
string $rawData
) : mixed
{
}
Description
Parse raw YAML data and return the parsed content.
This function loads a raw YAML string and returns the parsed content as an array or object.
Parameters
The raw YAML string to be parsed.
Return
The parsed YAML data, typically as an array or object.
Throws
If the YAML string cannot be parsed.
MagicObject\Util\Spicy
Declaration
Authors
- Vlad Andersen <vlad.andersen@gmail.com>
- Chris Wanstrath <chris@ozmm.org>
Links
Description
Class Spicy
This class is a modification of the Spyc project. The purpose of this modification is to integrate the class with other projects that use Composer, making it easy to use without requiring additional dependencies or code duplication. Additionally, code smells have been fixed to ensure the code remains clean and understandable when using SonarLint, thereby avoiding confusion for users when debugging code errors.
Constants
Properties
Declaration
Description
If set to true, forces YAML dump to enclose any string value in quotes. False by default.
Declaration
Description
If set to true, forces YAML load to use the syck_load function when possible.
False by default.
Declaration
Description
Indentation level for dumping YAML.
Declaration
Description
Word wrap length for dumping YAML.
Declaration
Description
Indicates if a group anchor is present in the YAML document.
Declaration
Description
Indicates if a group alias is present in the YAML document.
Declaration
Description
Current path being processed in the YAML structure.
Declaration
Description
Result of the YAML parsing or dumping process.
Declaration
Description
Placeholder for YAML literal blocks.
Declaration
Description
List of saved groups encountered during YAML parsing.
Declaration
Description
Current indentation level during parsing or dumping.
Declaration
Description
Path modifier to be applied after adding the current element.
Methods
Declaration
string $input
) : array
{
}
Description
Load a valid YAML string to Spicy.
Parameters
Return
Declaration
string $input,
array $options = array ( )
) : array
{
}
Description
Load a YAML file or string and convert it into a PHP array.
This method accepts a file path or a string containing YAML content and converts it into a PHP array. Options can be set to customize the behavior.
Parameters
Path to the YAML file or a string containing YAML content.
Optional settings to modify parsing behavior.
Return
The parsed YAML converted to a PHP array.
Declaration
string $input,
array $options = array ( )
) : array
{
}
Description
Load a YAML string and convert it into a PHP array.
This method accepts a string containing YAML content and converts it into a PHP array. Options can be set to customize the behavior.
Parameters
String containing YAML content.
Optional settings to modify parsing behavior.
Return
The parsed YAML converted to a PHP array.
Declaration
array $array,
int $indent = false,
int $wordwrap = false,
bool $noOpeningDashes = false
) : string
{
}
Description
Convert a PHP array to a YAML string.
This method converts a PHP array into a YAML string. You can customize the indentation and word wrapping. If not provided, the default values for indentation and word wrapping are 2 spaces and 40 characters, respectively.
Parameters
The PHP array to be converted.
Indentation size. Default is 2 spaces. Pass false to use the default.
Word wrap limit. Default is 40 characters. Pass 0 for no word wrap.
Whether to omit the opening dashes (---) from the YAML. Default is false.
Return
The YAML representation of the provided PHP array.
Declaration
mixed $key,
mixed $value,
int $indent,
int $previousKey = -1,
int $firstKey = 0,
array|null $sourceArray = null
) : string
{
}
Description
Converts a key-value pair to a YAML string.
This method attempts to convert a key and its corresponding value into a YAML-formatted string. It recursively processes arrays and objects.
Parameters
The key name.
The value associated with the key.
The current indentation level.
The previous key in the array (used for sequences).
The first key in the current array.
The source array being processed.
Return
The YAML representation of the key-value pair.
Declaration
array $array,
int $indent
) : string
{
}
Description
Converts an array to a YAML string with proper indentation.
This method iterates over an array and recursively converts each element into a YAML-formatted string.
Parameters
The array to be converted.
The current indentation level.
Return
The YAML representation of the array.
Declaration
mixed $key,
mixed $value,
int $indent,
int $previousKey = -1,
int $firstKey = 0,
array|null $sourceArray = null
) : string
{
}
Description
Converts a key-value pair to a YAML node string.
This method formats a key-value pair into a valid YAML node, applying literal blocks, folding, or quoting when necessary.
Parameters
The key name.
The value associated with the key.
The current indentation level.
The previous key in the array (used for sequences).
The first key in the current array.
The source array being processed.
Return
The YAML representation of the key-value pair as a node.
Declaration
string $value,
int $indent
) : string
{
}
Description
Creates a literal block for a YAML dump.
This method formats a given string as a YAML literal block, adding indentation and handling special characters or line breaks appropriately.
Parameters
The string to be converted into a literal block.
The current indentation level.
Return
The YAML-formatted literal block.
Declaration
string $value,
int $indent
) : string
{
}
Description
Folds a string of text if it exceeds the configured word wrap length.
This method wraps long strings in YAML using a folded style (>). If
the word wrap is disabled (set to 0), it returns the string as is.
Parameters
The string to be folded.
The current indentation level.
Return
The folded YAML string.
Declaration
string $value
) : bool
{
}
Description
Checks if a value represents a "true" word in YAML.
Recognized words: 'true', 'on', 'yes', 'y'.
Parameters
The value to check.
Return
True if the value matches a "true" word.
Declaration
string $value
) : bool
{
}
Description
Checks if a value represents a "false" word in YAML.
Recognized words: 'false', 'off', 'no', 'n'.
Parameters
The value to check.
Return
True if the value matches a "false" word.
Declaration
string $value
) : bool
{
}
Description
Checks if a value represents a "null" word in YAML.
Recognized words: 'null', '~'.
Parameters
The value to check.
Return
True if the value matches a "null" word.
Declaration
string $value
) : bool
{
}
Description
Checks if a value is a special YAML translation word.
This method checks if the value represents a "true", "false", or "null" word.
Parameters
The value to check.
Return
True if the value is a recognized YAML translation word.
Declaration
mixed
)
{
}
Description
Coerce a string into a native PHP type (boolean, null).
Based on the YAML 1.1 specification for boolean and null values. Reference: http://yaml.org/type/bool.html
Parameters
The value to coerce.
Declaration
array $words
) : array
{
}
Description
Translates a set of words into multiple cases (lowercase, uppercase, capitalized).
This ensures compatibility with YAML 1.1 coercion rules, which allow for different case variations of certain keywords (e.g., 'True', 'TRUE', 'true').
Parameters
The words to translate.
Return
An array of translated words with all case variations.
Declaration
string $input
) : array
{
}
Description
Loads a YAML file from the given path.
Parameters
The file path.
Return
The parsed YAML data.
Throws
If the file is not found.
Declaration
string $input
) : array
{
}
Description
Loads a YAML string and parses it into an array.
Parameters
The YAML string.
Return
The parsed YAML data.
Declaration
array $source
) : array
{
}
Description
Processes a source array of lines and converts it to a PHP array.
Parameters
The source lines.
Return
The parsed result as an associative array.
Declaration
string $input
) : array
{
}
Description
Converts a YAML string into an array of lines, removing any trailing carriage returns.
Parameters
The YAML string.
Return
An array of lines from the YAML input.
Declaration
string $text
) : string
{
}
Description
Fixes raw YAML input by ensuring proper formatting for list items (- key:) to avoid
indentation issues or malformed structures in the YAML.
The method scans each line and, if it detects a list item (- key:), it re-adjusts the line's
indentation to ensure it aligns correctly with the rest of the document.
Parameters
The raw YAML input string.
Return
The formatted YAML string with adjusted indentation for list items.
Declaration
string $line
) : array
{
}
Description
Parses a single line of YAML and returns the appropriate PHP structure for it.
This method determines the type of the line (mapped sequence, mapped value, array element, etc.) and converts it into a structured array representation.
Parameters
A single line from the YAML input.
Return
The parsed representation of the line.
Declaration
string $value
) : mixed
{
}
Description
Converts a YAML value string into the appropriate PHP type.
Supports scalar values (strings, integers, floats, booleans, null), arrays, and objects.
Handles quoted strings, inline mappings ({}), and inline sequences ([]).
Parameters
The YAML value to convert.
Return
The converted value as a native PHP type.
Declaration
string $inline
) : array
{
}
Description
Parses an inline YAML string and splits it into an array of elements.
Handles inline sequences ([]), mappings ({}), quoted strings, and empty strings,
ensuring they are correctly parsed without being broken by commas or special characters.
Parameters
The inline YAML string.
Return
Parsed components as an array.
Declaration
string $line,
int $lineIndent
) : bool
{
}
Description
Checks if a literal block should continue on the next line.
A literal block continues if the current line is blank or if it is more indented than the block's initial indentation level.
Parameters
The current line being processed.
The initial indentation level of the block.
Return
Returns true if the literal block should continue; otherwise, false.
Declaration
string $alias
) : mixed
{
}
Description
Retrieves the value of a YAML reference (alias).
The method looks up the alias in the saved groups and traverses the result array using the group path to return the associated value.
Parameters
The alias name to look up.
Return
The value associated with the alias, or null if not found.
Throws
If the alias is not found in the saved groups.
Declaration
array $array,
int $indent
) : bool
{
}
Description
Adds an array to the current path in an inline manner.
This method is used to add multiple key-value pairs from the given array at the specified indentation level while maintaining the current path.
Parameters
The array to add.
The current indentation level.
Return
Returns true if the array was added; otherwise, false.
Declaration
array $incomingData,
int $incomingIndent
) : $this
{
}
Description
Adds an array to the result at the specified indentation level.
This method processes incoming data and integrates it into the result array based on the current path and indentation. It also handles YAML anchors and aliases.
Parameters
The data to be added.
The indentation level of the incoming data.
Return
Returns the current instance for method chaining.
Declaration
string $line
) : string|false
{
}
Description
Check if the line starts a literal block.
This function checks if the line ends with a literal block indicator, either | or >.
It also excludes lines that contain HTML tags.
Parameters
The line to check.
Return
Returns | or > if it starts a literal block, false otherwise.
Declaration
string $line
) : bool
{
}
Description
Check if the next line is needed to complete the current one.
This function determines whether a following line is required to complete a structure, for instance when the line starts an array or contains a reference to one.
Parameters
The line to analyze.
Return
Returns true if the next line is needed, false otherwise.
Declaration
string $literalBlock,
string $line,
string $literalBlockStyle,
int $indent = -1
) : string
{
}
Description
Add a literal line to a literal block.
This function appends a line to the literal block. It handles indentation
and adjusts the line's content according to the specified literal block style (| or >).
Parameters
The existing literal block content.
The line to add.
The style of the literal block (| or >).
The indentation level to strip from the line (default: -1).
Return
The updated literal block with the added line.
Declaration
array $lineArray,
string $literalBlock
) : array
{
}
Description
Revert literal placeholders back to the full literal block.
This function searches for literal placeholders in the provided lines and replaces them with the actual content of the literal block.
Parameters
The array of lines to process.
The literal block content to insert.
Return
The updated line array with placeholders replaced.
Declaration
string $line,
int $indent = -1
) : string
{
}
Description
Strip indentation from a line.
This function removes leading whitespace from a line based on the provided indentation level.
Parameters
The line to strip.
The number of spaces to strip (default: -1).
Return
The line with indentation removed.
Declaration
int $indent
) : array
{
}
Description
Get the parent path for a given indentation level.
This function retrieves the path of the parent nodes based on the current indentation level.
Parameters
The current indentation level.
Return
The parent path for the given indentation level.
Declaration
string $line
) : bool
{
}
Description
Check if the line is a comment.
This function checks if a line is a comment, either starting with a # symbol
or containing a YAML document separator (---).
Parameters
The line to check.
Return
Returns true if the line is a comment, false otherwise.
Declaration
string $line
) : bool
{
}
Description
Check if the line is empty.
This function checks if a line is empty after trimming leading and trailing whitespace.
Parameters
The line to check.
Return
Returns true if the line is empty, false otherwise.
Declaration
string $line
) : bool
{
}
Description
Check if the line is an array element.
This function checks if a line starts with a dash (-), which is indicative
of an element in a YAML array.
Parameters
The line to check.
Return
Returns true if the line is an array element, false otherwise.
Declaration
string $value
) : string
{
}
Description
Remove quotes from a value.
This function removes single or double quotes from the start and end of a string, if present.
Parameters
The value to unquote.
Return
The value without quotes.
Declaration
string $line
) : bool
{
}
Description
Check if the line starts a mapped sequence.
This function checks if a line represents the start of a mapped sequence,
indicated by a - followed by a key and a colon (:).
Parameters
The line to check.
Return
Returns true if the line starts a mapped sequence, false otherwise.
Declaration
string $line
) : array
{
}
Description
Return the mapped sequence from a line.
This function processes the line to extract the key and create a corresponding array for a mapped sequence.
Parameters
The line to process.
Return
The array representing the mapped sequence.
Declaration
string $value
)
{
}
Description
Check if a value contains multiple keys.
This function checks if the value contains more than one key, indicated
by the presence of a colon (:) in a non-array or non-object structure.
Parameters
The value to check.
Throws
If there are too many keys in the value.
Declaration
string $line
) : array
{
}
Description
Return a mapped value from a line.
This function processes the line and returns a key-value pair for a mapped value.
Parameters
The line to process.
Return
The array with the key-value pair.
Declaration
string $line
) : bool
{
}
Description
Check if the line represents a mapped value (ends with a colon).
This function checks whether the line ends with a colon (:), indicating that
it is likely a mapped value in the YAML format.
Parameters
The line of text to check.
Return
Returns true if the line ends with a colon, false otherwise.
Declaration
string $line
) : bool
{
}
Description
Check if the line represents a plain array.
This function checks whether the line starts with an opening bracket ([)
and ends with a closing bracket (]), which is characteristic of a plain array
in YAML.
Parameters
The line of text to check.
Return
Returns true if the line is a plain array, false otherwise.
Declaration
string $line
) : mixed
{
}
Description
Return the parsed value of a plain array.
This function processes the line and converts it to its appropriate data type
based on the provided method _toType.
Parameters
The line representing the array element to be processed.
Return
The parsed value after conversion using _toType.
Declaration
string $line
) : array
{
}
Description
Return a key-value pair from a line.
This function extracts a key-value pair from a line. It handles cases where
the key is wrapped in quotes and also checks for special cases like 0 as key.
The value is processed to determine its data type.
Parameters
The line to parse.
Return
Returns an associative array with the key and value.
Declaration
string $line
) : array
{
}
Description
Return an array element from the line.
This function processes the line and trims the first character (usually a dash) before converting it to its appropriate type. It also checks if the value is an array and recursively handles nested elements.
Parameters
The line to process.
Return
Returns an array with the processed value.
Declaration
string $line
) : string|false
{
}
Description
Check if the line contains a group anchor or alias.
This function checks if a line contains a reference to a group anchor (denoted
by &) or alias (denoted by *). It can match anchors or aliases at the
beginning or end of the line, as well as inline references such as <<.
Parameters
The line to check for group anchors or aliases.
Return
Returns the group reference (anchor or alias) if found,
Declaration
string $line,
string $group
) : void
{
}
Description
Add a group anchor or alias to the internal properties.
This function processes a group identifier (anchor or alias) and stores it in the appropriate internal property, depending on whether it's an anchor ('&') or an alias ('*').
Parameters
The current line being processed (unused in this method).
The group string which can be an anchor or alias.
Return
Declaration
string $line,
string $group
) : string
{
}
Description
Strip a group identifier from a line of text.
This function removes the specified group identifier (anchor or alias) from the line and trims any extra spaces from the result.
Parameters
The line of text to process.
The group identifier to remove from the line.
Return
The line with the group identifier removed and trimmed.
Declaration
{
}
Description
Get the flag determining whether quotes are forced in the dump.
By default, the value is false. This flag indicates whether strings should
always be wrapped in quotes during the dumping process.
Return
The current setting of the flag for forced quotes.
Declaration
bool $dumpForceQuotes
) : self
{
}
Description
Set the flag for forcing quotes in the dump.
This function allows you to specify whether strings should always be enclosed in quotes during the dumping process.
Parameters
The value indicating whether to force quotes
Return
The current instance to allow method chaining.
Declaration
{
}
Description
Get the flag determining whether empty hashes are treated as objects.
By default, this value is false. This flag specifies whether empty hash
structures should be interpreted as objects instead of arrays.
Return
The current setting of the flag for empty hash as object.
Declaration
bool $emptyHashAsObject
) : self
{
}
Description
Set the flag for treating empty hashes as objects.
This function allows you to specify whether empty hash structures should be considered as objects (true) or as empty arrays (false).
Parameters
The value to indicate whether empty hashes
Return
The current instance to allow method chaining.
MagicObject\Util\TextConverter
Declaration
Package
MagicObject\UtilAuthors
- Kamshory
Links
Description
Class TextConverter
Converts text from one character encoding to another, specifically from ISO-8859-2 to UTF-8. This class handles character mappings for special characters and provides functionality for decoding HTML entities.
Properties
Declaration
Description
@var string $encodingFrom The source encoding (default is ISO-8859-2).
Declaration
Description
@var string $encodingTo The target encoding (default is UTF-8).
Declaration
Description
@var array $mapChrChr Mapping of character codes to corresponding character codes.
Declaration
Description
@var array $mapChrString Mapping of character codes to HTML entities.
Methods
Declaration
string|null $encodingFrom = null,
string|null $encodingTo = null
)
{
}
Description
TextConverter constructor.
Initializes the encoding settings.
Parameters
The source encoding (default is ISO-8859-2).
The target encoding (default is UTF-8).
Declaration
string $text
) : string
{
}
Description
Converts the given text from the source encoding to the target encoding.
Parameters
The input text to be converted.
Return
The converted text.
Declaration
{
}
Description
Prepares a mapping of characters based on the defined character mappings.
Return
The prepared character mapping array.
Declaration
callable $function,
array $array
) : array
{
}
Description
Maps an associative array using a callback function.
Parameters
The callback function to apply to each element.
The array to be mapped.
Return
The resulting array after mapping.
MagicObject\Util\WS\PicoWebsocketClient
Declaration
Description
WebSocket client.
By Paragi 2013, Simon Riget MIT license. This is a demonstration of a WebSocket client. If you find flaws in it, please let me know at simon.riget (at) gmail.
WebSockets use hybi10 frame encoding:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/63) |
|N|V|V|V| |S| | (if payload len == 126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+-------------------------------+
| Extended payload length continued, if payload len == 127 |
+---------------------------------------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
See: https://tools.ietf.org/rfc/rfc6455.txt or: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#section-4.2
Open WebSocket connection:
resource websocketOpen(string $host [,int $port [,array $headers [,string &$error_string [,int $timeout]]]])
Parameters
The host URL. It can be a domain name like www.example.com or an IP address, with port number. Local host example: 127.0.0.1:8080.
(Optional) The port number.
(Optional) Additional HTTP headers to attach to the request. For example, to parse a session cookie: "Cookie: SID=" . session_id().
(Optional) A referenced variable to store error messages, if any.
(Optional) The maximum time in seconds that a read operation will wait for an answer from the server. Default value is 10 seconds.
(Optional) Whether to use SSL for the connection. Default is false.
(Optional) Whether to use a persistent connection. Default is false.
(Optional) The path to connect to on the server. Default is '/'.
(Optional) A stream context resource to be used for the connection.
Return
Returns the WebSocket resource on success, or false on failure.
Methods
Declaration
string $host = '',
int $port = 80,
array $headers = array ( ),
string,
int $timeout = 10,
bool $ssl = false,
bool $persistant = false,
string $path = '/',
resource|null $context = null
) : resource|false
{
}
Description
Opens a WebSocket connection.
This method initiates a WebSocket connection to the specified host and port by sending an HTTP GET request with an upgrade header. If the server accepts the connection, it will respond with a 101 status code indicating the upgrade.
Parameters
The host URL (domain or IP address). Example: 'www.example.com'.
The port number. Defaults to 80 for HTTP and 443 for HTTPS.
Optional additional HTTP headers to include in the request.
Reference to a variable that will store error messages, if any.
The maximum time (in seconds) to wait for a server response. Defaults to 10.
Whether to use SSL for the connection. Defaults to false.
Whether to use a persistent connection. Defaults to false.
The path to connect to on the server. Defaults to '/'.
A stream context resource to be used for the connection.
Return
Returns the WebSocket resource on success, or false on failure.
Declaration
resource $sp,
string $data,
bool $final = true
) : int|false
{
}
Description
Sends a message through the WebSocket connection.
This method encodes the provided data into a WebSocket frame and sends it to the server.
Parameters
The WebSocket resource returned by websocketOpen.
The data to send to the server.
Indicates whether this is the final fragment of data. Defaults to true.
Return
The number of bytes written on success, or false on failure.
Declaration
resource $sp,
string $data,
bool $final = true
) : int|false
{
}
Description
Sends a WebSocket message through the specified socket.
Parameters
The socket resource to write to.
The data to send.
Indicates whether this is the final fragment.
Return
The number of bytes written, or false on failure.
Declaration
resource $sp,
string|null,
string|null
) : string|false
{
}
Description
Reads a message from the WebSocket connection.
This method reads a chunk of data from the server, handling the decoding of the WebSocket frame. It waits for the final chunk of data before returning.
Parameters
The WebSocket resource returned by websocketOpen.
Reference to a variable that will store an error code, if any.
Reference to a variable that will store an error message, if any.
Return
The received data on success, or false on failure.
Declaration
string $data
) : string
{
}
Description
Decodes a HyBi 10 WebSocket frame.
This method extracts and decodes the payload from a WebSocket frame according to the HyBi 10 specification. It handles masking if the frame is masked and supports both short and long payload lengths.
Parameters
The frame data to decode, typically received from the WebSocket.
Return
The decoded payload data. If the frame is not a valid WebSocket frame,
Declaration
string $type
) : int
{
}
Description
Gets the frame header byte for the specified frame type.
This method returns the appropriate header byte for different WebSocket frame types based on the HyBi 10 protocol. The frame header determines how the WebSocket payload is treated during transmission.
Parameters
The type of frame. Acceptable values are:
Return
The frame header byte corresponding to the specified type.
Declaration
string $payload,
string $type = 'text',
bool $masked = true
) : string|false
{
}
Description
Encodes the payload into a HyBi 10 WebSocket frame.
Parameters
The payload data to encode.
The type of frame (e.g., 'text', 'close', 'ping', 'pong'). Defaults to 'text'.
Whether to mask the payload. Defaults to true.
Return
The encoded WebSocket frame on success, or false on failure.